保存修改xml错误'ElementTree'对象没有属性'tag'

Saving modified xml error 'ElementTree' object has no attribute 'tag'

代码

当 运行 以下代码时,我无法将输出保存为 xml 文件,因为出现以下错误 AttributeError: 'ElementTree' object has no attribute 'tag'(在回溯中)。 SO 上有一个类似命名的问题,但我认为它与我的无关,因为它与从根节点解析而不是保存有关。

代码

import xml.etree.ElementTree as ET
print('\n'*5)

xmlfile = 'widget.XML'

tree = ET.parse(xmlfile)
root = tree.getroot()

#ET.dump(tree)# prints the xml file to console,shows xml indentation
print('\n'*2)
for elm in root.findall("./Common/ForceBinary"):
    print(elm.attrib)
    elm.attrib = {'type': 'integer', 'value': '0'}

with open("new_file.xml", "w") as f:
    f.write(ET.tostring(tree))

回溯

{'type': 'integer', 'value': '1'}
Traceback (most recent call last):
  File "/Users/user/Desktop/MY_PY/x_08.py", line 16, in <module>
    f.write(ET.tostring(tree))
  File "/Users/user/opt/anaconda3/lib/python3.7/xml/etree/ElementTree.py", line 1136, in tostring
    short_empty_elements=short_empty_elements)
  File "/Users/user/opt/anaconda3/lib/python3.7/xml/etree/ElementTree.py", line 777, in write
    short_empty_elements=short_empty_elements)
  File "/Users/user/opt/anaconda3/lib/python3.7/xml/etree/ElementTree.py", line 901, in _serialize_xml
    tag = elem.tag
AttributeError: 'ElementTree' object has no attribute 'tag'

在尝试了很多方法将输出写入 xml 文件后,这是行得通的行(我不知道为什么,如果有人有解释,我很乐意接受它作为答案)。

tree.write("sdn_edit2.xml")

ElementTree.tostring()Element 进行操作,这与 ElementTree 不同。您已经通过 tree.getroot() 提取了根节点 - 您只需要 ET.tostring(root) 即可。

API 之所以这样是因为 Element 旨在作为内存中解析的 XML 对象的数据结构,而 ElementTree 主要是只是一个序列化-反序列化助手(也许 Tree 命名不是最好的主意)以将那些 Element 与外界联系起来。

关于两者区别的相关问题: What is the difference between a ElementTree and an Element? (python xml)