How do I search an entire xml file for a specific text pattern and then replace each occurrence of that text with new text pattern in Python 3.5?
Ever
Caveats:
xml.etree.ElementTree
libraryThis is a modification from this excellent answer. The thing is, you need to read the XML file in and parse it.
import xml.etree.ElementTree as ET
with open('xmlfile.xml', encoding='latin-1') as f:
tree = ET.parse(f)
root = tree.getroot()
for elem in root.getiterator():
try:
elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
elem.text = elem.text.replace('FEATURE NUMBER', '123456')
except AttributeError:
pass
tree.write('output.xml', encoding='latin-1')
Note that you can change the encoding
parameter to something else such as: utf-8
, cp1252
, ISO-8859-1
, etc. Really depends on your system and file.