Element
对象没有.getroot()
方法。挂断该电话,该.tostring()
电话将正常工作:
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
仅.getroot()
当有ElementTree
实例时才需要使用。
其他说明:
这将产生一个 bytestring ,在Python 3中是该bytes
类型。 如果必须有一个str
对象,则有两个选择:
从UTF-8解码结果字节值: xmlstr.decode("utf8")
使用encoding='unicode'
; 这样可以避免编码/解码周期:
xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
如果要使用UTF-8编码的字节串值或使用Python 2,请考虑到ElementTree不能正确检测utf8
为标准XML编码,因此将添加一个<?xml version='1.0' encoding='utf8'?>
声明。如果要防止这种情况,请使用utf-8
或UTF-8
(带破折号)。使用时encoding="unicode"
不添加声明头。