Prabhu
Prabhu

Reputation: 3538

Setting value for a node in XML document in Python

I have a XML document "abc.xml":

I need to write a function replace(name, newvalue) which can replace the value node with tag 'name' with the new value and write it back to the disk. Is this possible in python? How should I do this?

Upvotes: 0

Views: 2638

Answers (2)

Ewan Todd
Ewan Todd

Reputation: 7312

import xml.dom.minidom
filename='abc.xml'
doc = xml.dom.minidom.parse(filename)
print doc.toxml()

c = doc.getElementsByTagName("c")
print c[0].toxml()
c[0].childNodes[0].nodeValue = 'zip'
print doc.toxml()

def replace(tagname, newvalue):
  '''doc is global, first occurrence of tagname gets it!'''
  doc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue = newvalue
replace('c', 'zit')

print doc.toxml()

See minidom primer and API Reference.

# cat abc.xml
<root>
  <a>
    <c>zap</c>
  </a>
  <b>
  </b>
</root>

Upvotes: 2

Mattias Nilsson
Mattias Nilsson

Reputation: 3757

Sure it is possible. The xml.etree.ElementTree module will help you with parsing XML, finding tags and replacing values.

If you know a little bit more about the XML file you want to change, you can probably make the task a bit easier than if you need to write a generic function that will handle any XML file.

If you are already familiar with DOM parsing, there's a xml.dom package to use instead of the ElementTree one.

Upvotes: 2

Related Questions