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



