sourcecode

Python 요소 변환트리에서 문자열로

copyscript 2023. 9. 16. 09:49
반응형

Python 요소 변환트리에서 문자열로

내가 전화할때마다ElementTree.tostring(e), 다음 오류 메시지가 나타납니다.

AttributeError: 'Element' object has no attribute 'getroot'

요소를 변환하는 다른 방법이 있습니까?개체를 XML 문자열로 트리하시겠습니까?

추적:

Traceback (most recent call last):
  File "Development/Python/REObjectSort/REObjectResolver.py", line 145, in <module>
    cm = integrateDataWithCsv(cm, csvm)
  File "Development/Python/REObjectSort/REObjectResolver.py", line 137, in integrateDataWithCsv
    xmlstr = ElementTree.tostring(et.getroot(),encoding='utf8',method='xml')
AttributeError: 'Element' object has no attribute 'getroot'

Element물건이 없습니다..getroot()방법.통화를 중단하면 통화가 가능합니다.

xmlstr = ElementTree.tostring(et, encoding='utf8')

사용하기만 하면 됩니다..getroot()를 들면 말이죠

기타 참고 사항:

  • 이것은 파이썬 3에서 다음과 같은 바이테스트링을 생성합니다.bytes유형.
    당신이 꼭 필요하다면.strobject, 두 가지 옵션이 있습니다.

    1. UTF-8에서 결과 바이트 값을 디코딩합니다.xmlstr.decode("utf8")

    2. 사용하다encoding='unicode'; 이렇게 하면 인코딩/디코드 주기를 피할 수 있습니다.

      xmlstr = ElementTree.tostring(et, encoding='unicode')
      
  • 테스트 문자열 값으로 UTF-8을 인코딩하고 싶거나 Python 2를 사용하는 경우 해당 Element를 고려합니다.트리가 제대로 감지되지 않음utf8표준 XML 인코딩으로서, 그래서 그것은.<?xml version='1.0' encoding='utf8'?>선언. 사용utf-8아니면UTF-8이 일을 막으려면 말이죠사용시encoding="unicode"선언 헤더가 추가되지 않습니다.

변환 방법ElementTree.Element줄로?

Python 3의 경우:

xml_str = ElementTree.tostring(xml, encoding='unicode')

Python 2의 경우:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

사용 예시 (Python 3)

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml, encoding='unicode')
print(xml_str)

출력:

<Person Name="John" />

설명.

ElementTree.tostring() 는 기본적으로 Python 2 & 3의 bytestring을 반환합니다.이 문제는 파이썬 3이 문자열에 유니코드를 사용하는 것으로 전환했기 때문입니다.

파이썬 2에서는 텍스트 데이터와 이진 데이터 모두에 타입을 사용할 수 있습니다.불행히도 두 개념의 결합으로 인해 취약한 코드가 발생할 수 있으며, 때로는 데이터 유형에 따라 작동하지 않을 수도 있습니다. [...]

[파이썬3]는 텍스트와 바이너리 데이터의 구분을 보다 명확하고 명확하게 하기 위해 텍스트와 바이너리 데이터를 맹목적으로 혼합할 수 없는 구분형으로 만들었습니다.

출처: Python 2 코드를 Python 3으로 포팅

어떤 버전의 파이썬이 사용되고 있는지 알고 있다면 인코딩을 다음과 같이 지정해야 합니다.unicode아니면utf-8. 참고로, 저는 다음과 같은 것들을 비교해 보았습니다..tostring()Python 2와 Python 3 사이의 결과입니다.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

참고: Python 2와 3 둘 다 호환되지만, Christopher Rucinski는 이 방법이 라틴어가 아닌 문자를 다룰실패한다고 지적했습니다.

Martijn Peters에게 감사드립니다.str데이터 유형이 Python 2와 3 사이에서 변경되었습니다.


str()을 사용하지 않는 이유는 무엇입니까?

대부분의 시나리오에서는 을 사용하여 개체를 문자열로 변환하는 "정통적인" 방법을 사용합니다.하지만 사용하는것은str()와 함께Element메모리에서 개체의 위치를 개체 데이터의 문자열 표현이 아닌 16진수로 반환합니다.

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>

라틴어가 아닌 답변 확장

@Stevoisiak의 답변 확장 및 라틴어가 아닌 캐릭터 처리한 가지 방법만 라틴어가 아닌 문자를 사용자에게 표시합니다.하나의 방법은 파이썬 3과 파이썬 2 둘 다 다릅니다.

인풋

xml = ElementTree.fromstring('<Person Name="크리스" />')
xml = ElementTree.Element("Person", Name="크리스")  # Read Note about Python 2

에서 : Python 2 을 할 에서는 를 호출할 때toString(...)드 할당,당xml와 함께ElementTree.Element("Person", Name="크리스")오류를 일으킬 겁니다

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

산출량

ElementTree.tostring(xml)
# Python 3 (크리스): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (크리스): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (크리스): <Person Name="크리스" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (크리스): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (크리스): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (크리스): <Person Name="크리스" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (크리스): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (크리스): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

파이썬 3.8에서도 같은 문제가 있었는데 이전의 답변 중에 해결된 것은 없었습니다.문제는 Element가트리는 모듈의 이름이자 그 안에 있는 클래스의 이름입니다.별칭을 사용하면 다음을 명확하게 알 수 있습니다.

from xml.etree.ElementTree import ElementTree
import xml.etree.ElementTree as XET
...
ElementTree.tostring(...)  # Attribute-error
XET.tostring(...)          # Works

입력 샘플 파일 내용:

<?xml version="1.0" encoding="ISO-8859-1"?>
<UPDATE>
<DATA><SET_DOC ID="249865"/></DATA>
</UPDATE>

특정 요소에 대한 접근 코드를 문자열로 지정하려면:

import lxml.etree as ET

samplexml = ET.parse(r"D:\sample.xml")

sampleroot = samplexml.getroot()

for dataElement in sampleroot.iter('DATA'):
    updatext = ET.tostring(dataElement)
    print(updatext)

출력:

b'<DATA><SET_DOC ID="249865"/></DATA>\n'

위해 에 XML 파일을 사용할 수 .print(xml.etree.ElementTree.tostring(e))을 사용할 수 .dump다음과 같이:

xml.etree.ElementTree.dump(e)

은 합니다 은 합니다 은 .Element그리고.ElementTree과 같은 e, 가 가 는 없습니다.getroot.

문서에는 다음과 같이 나와 있습니다.

xml.etree.ElementTree.dump(elem)

를 를 에 에 씁니다.sys.stdout. 이 함수는 디버깅에만 사용해야 합니다.

정확한 출력 형식은 구현에 따라 다릅니다.이 버전에서는 일반 XML 파일로 작성됩니다.

elem요소 트리 또는 개별 요소입니다.

3.8 버전에서 변경됨: Thedump()function은 이제 사용자가 지정한 속성 순서를 유지합니다.

언급URL : https://stackoverflow.com/questions/15304229/convert-python-elementtree-to-string

반응형