How to convert ElementTree.Elementto string?
For Python 3:
xml_str = ElementTree.tostring(xml, encoding='unicode')
For Python 2:
xml_str = ElementTree.tostring(xml, encoding='utf-8')
For compatibility with Python 2 and 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)
:
<Person Name="John" />
, , ElementTree.tostring() Python 2 3. Python 3, Unicode .
Python 2 str . , , , . [...]
, [Python 3] , .
: Python 2 Python 3
, Python , unicode utf-8. , Python 2 3, decode() .
.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" />
Martijn Peters , str Python 2 3.
str()?
str() " " . , Element , .
from xml.etree import ElementTree
xml = ElementTree.Element("Person", Name="John")
print(str(xml))