Find and Replace Values in XML using Python Find and Replace Values in XML using Python python python

Find and Replace Values in XML using Python


The basics:

from xml.etree import ElementTree as ettree = et.parse(datafile)tree.find('idinfo/timeperd/timeinfo/rngdates/begdate').text = '1/1/2011'tree.find('idinfo/timeperd/timeinfo/rngdates/enddate').text = '1/1/2011'tree.write(datafile)

You can shorten the path if the tag name is unique. This syntax finds the first node at any depth level in the tree.

tree.find('.//begdate').text = '1/1/2011'tree.find('.//enddate').text = '1/1/2011'

Also, read the documentation, esp. the XPath support for locating nodes.


If you just want to replace the bits enclosed with %, then this isn't really an XML problem. You can easily do it with regex:

import rexmlstring = open('myxmldocument.xml', 'r').read()substitutions = {'SITEDESCR': 'myvalue', ...}pattern = re.compile(r'%([^%]+)%')xmlstring = re.sub(pattern, lambda m: substitutions[m.group(1)], xmlstring)


To replace the placeholders all you need is to read the file line by line and replace:

for line in open(template_file_name,'r'):  output_line = line  output_line = string.replace(output_line, placeholder, value)  print output_line