복붙노트

[PYTHON] Python ElementTree를 문자열로 변환

PYTHON

Python ElementTree를 문자열로 변환

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 <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'

해결법

  1. ==============================

    1.요소 객체에는 .getroot () 메소드가 없습니다. 전화를 끊고 .tostring () 호출이 작동합니다.

    요소 객체에는 .getroot () 메소드가 없습니다. 전화를 끊고 .tostring () 호출이 작동합니다.

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

    2.파이썬 2와 3 모두에서 작동하는 솔루션의 경우 .tostring ()과 .decode ()를 사용하십시오.

    파이썬 2와 3 모두에서 작동하는 솔루션의 경우 .tostring ()과 .decode ()를 사용하십시오.

    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)
    

    산출:

    <Person Name="John" />
    

    이름에서 알 수 있듯이 ElementTree.tostring ()은 기본적으로 문자열을 반환하지 않습니다. 기본 동작은 바이트 테스트를 생성하는 것입니다. 이것이 파이썬 2에서는 문제가 아니었지만, 파이썬 3에서는 두 가지 유형이 더 뚜렷했습니다.

    출처 : 파이썬 2 코드를 파이썬 3에 이식

    decode ()를 사용하여 우리의 바이트 체크를 일반 텍스트로 명시 적으로 변환함으로써이 모호성을 해결할 수 있습니다. 이렇게하면 Python 2 및 Python 3과의 호환성이 보장됩니다.

    참고로 파이썬 2와 파이썬 3 사이에서 .tostring () 결과를 비교해 보았습니다.

    ElementTree.tostring(xml).decode()
    # Python 3: <Person Name="John" />
    # Python 2: <Person Name="John" />
    
    ElementTree.tostring(xml, encoding='unicode', method='xml')
    # Python 3: <Person Name="John" />
    # Python 2: LookupError: unknown encoding: unicode
    
    ElementTree.tostring(xml, encoding='utf-8', method='xml')
    # Python 3: b'<Person Name="John" />'
    # Python 2: <Person Name="John" />
    
    ElementTree.tostring(xml, encoding='utf8', method='xml')
    # Python 3: b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n<Person Name="John" />'
    # Python 2: <?xml version='1.0' encoding='utf8'?>
    #           <Person Name="John" />
    

    파이썬 2와 3 사이에서 str 데이터 유형이 변경되었음을 지적한 Martijn Peters에게 감사드립니다.

    대부분의 시나리오에서 str ()을 사용하면 객체를 문자열로 변환하는 "표준적인"방법이됩니다. 불행히도 Element와 함께이 객체를 사용하면 객체 데이터의 문자열 표현이 아니라 객체의 위치가 메모리에 hexstring으로 반환됩니다.

    from xml.etree import ElementTree
    
    xml = ElementTree.Element("Person", Name="John")
    print(str(xml))  # <Element 'Person' at 0x00497A80>
    
  3. from https://stackoverflow.com/questions/15304229/convert-python-elementtree-to-string by cc-by-sa and MIT license