Convert Python ElementTree to string

前端 未结 3 1922
独厮守ぢ
独厮守ぢ 2020-12-04 11:04

Whenever I call ElementTree.tostring(e), I get the following error message:

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


        
3条回答
  •  醉酒成梦
    2020-12-04 11:31

    Non-Latin Answer Extension

    Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

    Input

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

    NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="크리스")will raise an error...

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

    Output

    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): 
    
    

提交回复
热议问题