I am looking to edit XML files using python. I want to find and replace keywords in the tags. In the past, a co-worker had set up template XML files and used a “find and replace” program to replace these key words. I want to use python to find and replace these key words with values. I have been teaching myself the Elementtree module, but I am having trouble trying to do a find and replace. I have attached a snid-bit of my XML file. You will seen some variables surrounded by % (ie %SITEDESCR%) These are the words I want to replace and then save the XML to a new file. Any help or suggestions would be great.


 <origin>My Company</origin>
 <geoform>vector digital data</geoform>
 <abstract>This dataset represents the mapped polygons developed from the field data for the %SITEDESCR%.</abstract>
 <purpose>This dataset was created to accompany some stuff.</purpose>
 <current>ground condition</current>

The basics:

from xml.etree import ElementTree as et
tree = et.parse(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.


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 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)

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 

You can modify in place and safely do so with xpath rather than full paths or worse, regex. See below and check out the docs on etree

from lxml import etree
raw = """
nodes = etree.fromstring(raw.strip())
shh = [setattr(x, "text", "DATE: 2021-01-01") for x in nodes.xpath(".//*[.='%begdate%']")]
['DATE: 2021-01-01']