Whenever I call ElementTree.tostring(e), I get the following error message:
AttributeError: \'Element\' object has no attribute \'getroot\'
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, assigningxmlwithElementTree.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):