如何将ElementTree.Element转换为字符串?
对于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)
输出:
解释
不管名称意味着什么,^{}在Python 2&3中默认返回bytestring。这是Python 3中的一个问题,即uses Unicode for strings。In Python 2 you could use the str type for both text and binary data.
Unfortunately this confluence of two different concepts could lead to
brittle code which sometimes worked for either kind of data, sometimes
not. [...]
To make the distinction between text