3

I am trying to find examples of how to change an existing xml files Element Value.

Using the following xml example:

<book>
  <title>My Book</title>
  <author>John Smith</author>
</book>

If I wanted to replace the author element value 'John Smith' with 'Jim Johnson' in a Python script using DOM, how would I go about doing so? I've tried to look for examples on this, but have failed in doing so. Any help would be greatly appreciated.

Regards, Rylic

1 Answer 1

5

Presuming

s = '''
<book>
  <title>My Book</title>
  <author>John Smith</author>
</book>'''

DOM would look like:

from xml.dom import minidom

dom = minidom.parseString(s) # or parse(filename_or_file)
for author in dom.getElementsByTagName('author'):
    author.childNodes = [dom.createTextNode("Jane Smith")]

But I'd encourage you to look into ElementTree, it makes working with XML a breeze:

from xml.etree import ElementTree

et = ElementTree.fromstring(s) # or parse(filename_or_file)
for author in et.findall('author'):
    author.text = "Jane Smith"
Sign up to request clarification or add additional context in comments.

4 Comments

IThanks for your help. I used ElementTree as you suggested, and it works fine. I am able to write to the xml file with the change that was needed. I did notice that when the file is written to, a lock is put on the file. I am presuming that the file is still open for writting. Is there a close method to unlock the file after writting to it with ElementTree?
@rylic38 How are you handling writing the file? Can you paste a code sample up on pastie.org?
pastie.org is unfortunetly not accessable at work. I'll try to add it here: import os import xml from xml.etree import ElementTree as et path = "C:\\temp\\books.xml" tree = et.parse(path) for author in tree.findall('author'): author.text = "Jane Doe" tree.write(path) When I run this line by line at the command line, the xml file is written to, but is locked. If I exit python, the file is released, and I can then see the change.
The format came out unreadable, I seperated each line with "". I hope that makes it more readable. import os *** import xml *** from xml.etree import ElementTree as et path = "C:\\temp\\books.xml"*** tree = et.parse(path)*** for author in tree.findall('author'): *** author.text = "Jane Doe" *** tree.write(path) ***

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.