如何将ElementTree.Element 转换为字符串?
对于 Python 3:
xml_str = ElementTree.tostring(xml, encoding='unicode')
对于 Python 2:
xml_str = ElementTree.tostring(xml, encoding='utf-8')
以下内容同时兼容 Python 2 和 3,但 only works for Latin characters:
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 中的一个问题,uses Unicode for strings。
在 Python 2 中,您可以将 str 类型用于文本和二进制数据。
不幸的是,这两种不同概念的融合可能导致
有时适用于任何一种数据的脆弱代码,有时
不是。 [...]
为了使文本和二进制数据之间的区别更加清晰和明显,[Python 3] 使文本和二进制数据成为不能盲目混合在一起的不同类型。
来源:Porting Python 2 Code to 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() 将是“cannonical”将对象转换为字符串的方式。不幸的是,将它与Element 一起使用会以十六进制字符串的形式返回对象在内存中的位置,而不是对象数据的字符串表示形式。
from xml.etree import ElementTree
xml = ElementTree.Element("Person", Name="John")
print(str(xml)) # <Element 'Person' at 0x00497A80>