Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python ElementTree.tostring(tree)失败,但ElementTree.tostring(tree.getroot())正常,无法描述差异_Python_Elementtree - Fatal编程技术网

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对象吗

谢谢你宝贵的反馈


Simon

ET.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()