将Python ElementTree转换为字符串
每当我致电时ElementTree.tostring(e)
,都会收到以下错误消息:
AttributeError: 'Element' object has no attribute 'getroot'
还有其他方法可以将ElementTree对象转换为XML字符串吗?
追溯:
Traceback (most recent call last):
File "Development/Python/REObjectSort/REObjectResolver.py", line 145, in <module>
cm = integrateDataWithCsv(cm, csvm)
File "Development/Python/REObjectSort/REObjectResolver.py", line 137, in integrateDataWithCsv
xmlstr = ElementTree.tostring(et.getroot(),encoding='utf8',method='xml')
AttributeError: 'Element' object has no attribute 'getroot'
-
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"
不添加声明头。
-