XML 属性修改未保存

XML Attribute modification not being saved

我有以下代码:

def incrCount(root):
    root.attrib['count'] = int(root.attrib['count']) + 1
    # root.set('count', int(root.attrib['count']) + 1)

root = getXMLRoot('test.xml')
incrCount(root)
print root.attrib['count']

当我 运行 它时,打印了正确的值,但在执行结束时该更改在文件中永远不可见。以上两种方法我都试过了,都没有成功。谁能指出我哪里出错了?

如文档中所示(19.7.1.4. Modifying an XML File), you need to write back to file after all modification operations has been performed. Assuming that root references instance of ElementTree, you can use ElementTree.write() 用于此目的的方法:

.....
root = getXMLRoot('test.xml')
incrCount(root)
print root.attrib['count']
root.write('test.xml')