1

I've been working with python's xml.etree.ElementTree library for a bit, mostly playing around with it. I've noticed, however, that python seems to load the file into memory and edit it there, then flush it, and continue using the unedited version. For example, if my program adds an element to an XML file, then iterates through that XML file, it won't see the addition that it made earlier.

Here's the condensed version of my code:

for adding to the file:

import xml.etree.ElementTree as ET
tree = et.parse("file.xml")
root = tree.getroot()
newel = ET.Element("element", tag=foo, )
newel.text = bar
root.append(newel)
tree.write("file.xml")
for child in root:
        if child.get("tag") == foo:
            print(child.text)

Am I doing something wrong, or what's a good way of 'refreshing', so to speak, the XML file in the program so when I iterate through the program with a for loop I can see my new element?

I am using python 3.5.

prongs95
  • 15
  • 3
  • I have seen [this](http://stackoverflow.com/questions/27829575/python-refresh-file-from-disk), but it doesn't seem to apply. – prongs95 Dec 01 '16 at 00:33

1 Answers1

0

This has nothing to do with refreshing or flushing. The Element constructor's signature is:

    __init__(self, tag, attrib={}, **extra)

You are passing in tag as a named argument in addition to implicitly specifying it as "element". Assuming you want tag to be an element attribute (based on how you are attempting to retrieve it with Element.get), the following should work (with some additional corrections):

foo = "foo"
bar = "bar"

import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
newel = ET.Element("element", {"tag": foo})
newel.text = bar
root.append(newel)
tree.write("file.xml")
for child in root:
        if child.get("tag") == foo:
            print(child.text)
Ben
  • 2,422
  • 2
  • 16
  • 23