Find and Replace Values in XML using Python

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.

Leave a Comment