python ElementTree.tostring(tree)失败,但ElementTree.tostring(tree.getroot())正常,无法描述差异
我不理解我在下面的代码示例中添加的失败python ElementTree.tostring(tree)失败,但ElementTree.tostring(tree.getroot())正常,无法描述差异,python,elementtree,Python,Elementtree,我不理解我在下面的代码示例中添加的失败 import xml.etree.ElementTree as ET with open('sheet_short.xml','r') as f: tree = ET.parse(f) # # some processing # xml_str = ET.tostring(tree) 代码失败,并显示错误消息 AttributeError: 'ElementTree' object has no attribute 'tag' 搜索了一点后,我在
import xml.etree.ElementTree as ET
with open('sheet_short.xml','r') as f:
tree = ET.parse(f)
#
# some processing
#
xml_str = ET.tostring(tree)
代码失败,并显示错误消息
AttributeError: 'ElementTree' object has no attribute 'tag'
搜索了一点后,我在一个链接上结束,该链接声明我应该使用getroot,所以我将最后一行替换为
xml_str = ET.tostring(tree.getroot())
现在一切都好了,但我不知道为什么它最初会失败
是因为parse
返回一个ElemenTree对象,而tostring
需要一个element对象吗
谢谢你宝贵的反馈
SimonET.tostring需要一个xml元素,而您要将它传递给整个树。它们不是同一类的对象
tree
是一个xml.etree.ElementTree.ElementTree
对象,而tree.getroot()
是一个xml.etree.ElementTree.Element
对象。和ElementTree。toString
需要元素
参数(不是ElementTree
)
另一方面,tree
有一个write
方法:
out = io.BytesIO()
tree.write(out)
xml_str = out.getvalue().decode()