未保存XML属性修改

时间:2016-04-20 03:03:05

标签: python xml xml-attribute

我有以下代码:

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']

当我运行它时,会打印正确的值,但在执行结束时该文件中永远不会显示该更改。我上面尝试过两种方法都没有成功。谁能指出我犯错的地方?

1 个答案:

答案 0 :(得分:1)

如文档(19.7.1.4. Modifying an XML File)中所示,您需要在执行所有修改操作后写回文件。假设root引用ElementTree的实例,您可以使用ElementTree.write()方法实现此目的:

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