Posted on Leave a comment

Python Script to Replace String in XML File

Here is a Python script that can be used to replace a specific string in an XML file:

import xml.etree.ElementTree as ET

# specify the input and output file paths
xml_file = 'input.xml'
output_file = 'output.xml'

# specify the string to be replaced and its replacement
old_string = 'old_string'
new_string = 'new_string'

# parse the XML file
tree = ET.parse(xml_file)
root = tree.getroot()

# search for the string in the XML elements and replace it
for elem in root.iter():
    if old_string in elem.text:
        elem.text = elem.text.replace(old_string, new_string)
    for at in elem.attrib:
        if old_string in elem.attrib[at]:
            elem.attrib[at] = elem.attrib[at].replace(old_string, new_string)

# write the modified XML to the output file
tree.write(output_file)

Please note that this script will replace all instances of the specified string in the XML file, both in the element text and in the element attributes. If you want to replace only in a specific element you can use the xpath functionality in the ElementTree library.

root.find('.//element_name').text = new_string

This will replace the string only in the element_name element.

Leave a Reply

Your email address will not be published. Required fields are marked *