<질문>
ElementTree.tostring (e)을 호출 할 때마다 다음과 같은 오류 메시지가 나타납니다.
AttributeError: 'Element' object has no attribute 'getroot'
ElementTree 객체를 XML 문자열로 변환하는 다른 방법이 있습니까?
역 추적:
Traceback (most recent call last):
File "Development/Python/REObjectSort/REObjectResolver.py", line 145, in
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'
<답변1>
요소 객체에는 .getroot () 메서드가 없습니다. 해당 호출을 삭제하면 .tostring () 호출이 작동합니다.
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
<답변2>
Python 3 :
xml_str = ElementTree.tostring(xml, encoding='unicode')
Python 2 :
xml_str = ElementTree.tostring(xml, encoding='utf-8')
Python 2 및 3과의 호환성을 위해
xml_str = ElementTree.tostring(xml).decode()
from xml.etree import ElementTree
xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)
산출:
이름이 의미하는 바에도 불구하고 ElementTree.tostring ()은 기본적으로 Python 2 및 3에서 바이트 문자열을 반환합니다. 이것은 문자열에 유니 코드를 사용하는 Python 3의 문제입니다.
Python 2에서는 텍스트 및 이진 데이터 모두에 str 유형을 사용할 수 있습니다. 불행히도 두 가지 다른 개념의 이러한 합류는 때때로 두 종류의 데이터에 대해 작동하는 깨지기 쉬운 코드로 이어질 수 있습니다. [...] 텍스트와 이진 데이터를 더 명확하고 분명하게 구분하기 위해 [Python 3]은 맹목적으로 혼합 할 수없는 텍스트와 이진 데이터를 구별하는 유형을 만들었습니다.
출처 : Python 2 코드를 Python 3으로 포팅
사용중인 Python 버전을 알고 있다면 인코딩을 unicode 또는 utf-8로 지정할 수 있습니다. 그렇지 않고 Python 2와 3과의 호환성이 필요한 경우 decode ()를 사용하여 올바른 유형으로 변환 할 수 있습니다.
참고로 Python 2와 Python 3의 .tostring () 결과를 비교했습니다.
ElementTree.tostring(xml)
# Python 3: b' '
# Python 2:
ElementTree.tostring(xml, encoding='unicode')
# Python 3:
# Python 2: LookupError: unknown encoding: unicode
ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b' '
# Python 2:
ElementTree.tostring(xml).decode()
# Python 3:
# Python 2:
str 데이터 유형이 Python 2와 3 사이에서 변경되었음을 지적한 Martijn Peters에게 감사드립니다.
대부분의 시나리오에서 str ()을 사용하는 것은 객체를 문자열로 변환하는 "정규적인"방법입니다. 불행히도이를 Element와 함께 사용하면 객체 데이터의 문자열 표현이 아니라 메모리에서 객체의 위치를 16 진수 문자열로 반환합니다.
from xml.etree import ElementTree
xml = ElementTree.Element("Person", Name="John")
print(str(xml)) #
<답변3>
@Stevoisiak의 답변에 대한 확장 및 비 라틴 문자 처리. 비 라틴어 문자는 한 가지 방법으로 만 표시됩니다. 한 가지 방법은 Python 3과 Python 2에서 모두 다릅니다.
입력
xml = ElementTree.fromstring(' ')
xml = ElementTree.Element("Person", Name="크리스") # Read Note about Python 2
참고 : Python 2에서 toString (...) 코드를 호출 할 때 ElementTree.Element ( "Person", Name = "크리스")로 xml을 할당하면 오류가 발생합니다. UnicodeDecodeError : 'ascii'codec ca n't 위치 0에서 0xed 바이트 디코딩 : 범위에없는 서수 (128)
산출
ElementTree.tostring(xml)
# Python 3 (크리스): b' '
# Python 3 (John): b' '
# Python 2 (크리스):
# Python 2 (John):
ElementTree.tostring(xml, encoding='unicode')
# Python 3 (크리스): <-------- Python 3
# Python 3 (John):
# Python 2 (크리스): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode
ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (크리스): b' '
# Python 3 (John): b' '
# Python 2 (크리스): <-------- Python 2
# Python 2 (John):
ElementTree.tostring(xml).decode()
# Python 3 (크리스):
# Python 3 (John):
# Python 2 (크리스):
# Python 2 (John):
'개발 > Python' 카테고리의 다른 글
emit () 및 pyqtSignal ()의 PyQt 적절한 사용 (0) | 2020.09.22 |
---|---|
파이썬을 사용하여 실제 사용자 홈 디렉토리를 찾는 방법은 무엇입니까? (0) | 2020.09.19 |
lxml의 태그 안의 모든 텍스트 가져 오기 (0) | 2020.09.19 |
목록의 모든 항목이 없음인지 확인하는 방법은 무엇입니까? (0) | 2020.09.19 |