2

I am using an XML document to keep track of user information, in python. I was doing some tests in IDLE, but for some reason the XML is not being edited. I looked all over the python docs and I couldn't find the issue at all. Here is what I was typing:

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('./usrData.xml')
>>> root = tree.getroot()
>>> root.tag
meritTracker 

Up until this part, everything was working fine. I know it read the right document, because it showed the right tag. But then:

>>>newElement = ET.Element('Name')
>>>ET.SubElement(root, newElement)
<Element <Element 'Name' at 0x1022119f0> at 0x102211a48>

The XML Doc doesn't change at all. I then reset IDLE, and did this:

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('./usrData.xml')
>>> root = tree.getroot()
>>> root.tag
meritTracker 
>>>newElement = ET.Element('Name')
>>>root.append(newElement)
>>>root.getchildren()

Still nothing. Then I tried the long way around:

>>> file = open('./usrData.xml','r+')
>>> tree = ET.parse(file)
>>> root = tree.getroot()
>>> root.append(ET.Element('Name'))
>>> root.getchildren()
[<Element 'Name' at 0x101756680>]

However, the XML still did not change! How can I fix this?

Note: Im running Python 3.3 on Mac OS X 10.8

1 Answer 1

3

You need to write your output back to the file:

tree.write('output.xml')
Sign up to request clarification or add additional context in comments.

3 Comments

Do I write it out after every change or only when the program is completed? In other words, does Python store the changes in local memory?
@elder4222 no just when the program is completed, you should be finished editing your tree before you need to use it again. Is that not the case here?
yes, that is the case. I was just confirming. Thanks for all your help guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.