Question

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?

Was it helpful?

Solution

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>

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top