0

I have the following code:

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

when I run it, the correct value is printed but that change is never visible in the file at the end of execution. I have tried both methods above to no success. Can anyone point out where I made the mistake?

mjr
  • 97
  • 2
  • 11
  • 1
    The changes are only made in memory. If you want them to go into a file you'll need to write them yourself. Use [tostring](https://docs.python.org/3.5/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring) and write the result to a file opened with `'wb'` mode. – bbayles Apr 20 '16 at 03:07
  • @bbayles I figured I could just modify the file directly. But I was hoping to find something in the ET module. Oh well. In that case when is the method set ever useful? – mjr Apr 20 '16 at 03:16
  • The file is read from disk as a stream of text and then parsed into nodes in memory. When it is saved (explicitly), the reverse happens. Consider the overhead in shuffling the rest of the text to add or modify an attribute in a large file. – Mike Apr 20 '16 at 03:45

1 Answers1

1

As exemplified in the documentation (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() method for this purpose :

.....
root = getXMLRoot('test.xml')
incrCount(root)
print root.attrib['count']
root.write('test.xml')
har07
  • 88,338
  • 12
  • 84
  • 137