Find and Replace Values in XML using Python
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 re
xmlstring = open('myxmldocument.xml', 'r').read()
substitutions = {'SITEDESCR': 'myvalue', ...}
pattern = re.compile(r'%([^%]+)%')
xmlstring = re.sub(pattern, lambda m: substitutions[m.group(1)], xmlstring)
The basics:
from xml.etree import ElementTree as et
tree = 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.