How To Edit An Xml File In Python?
I have a resx file that uses XML with a bunch of data that looks like this: Text 1 &
Solution 1:
Which XML parser to choose is up to you, but here is how you can approach this problem with xml.etree.ElementTree
: the idea is to iterate over all data
nodes, get the name
attribute value from the .attrib
dictionary, locate the value
element inside and set the .text
appropriately:
import xml.etree.ElementTree as ET
data = """<parent><dataname="key_first"xml:space="preserve"><value>Text 1</value></data><dataname="key_second"xml:space="preserve"><value>Text 2</value></data><dataname="key_third"xml:space="preserve"><value>Text 3</value></data></parent>"""
tree = ET.fromstring(data)
for data in tree.findall("data"):
name = data.attrib["name"]
value = data.find("value")
value.text = "[%s] %s" % (name, value.text)
print(ET.tostring(tree))
Prints:
<parent><dataname="key_first"xml:space="preserve"><value>[key_first] Text 1</value></data><dataname="key_second"xml:space="preserve"><value>[key_second] Text 2</value></data><dataname="key_third"xml:space="preserve"><value>[key_third] Text 3</value></data></parent>
Solution 2:
Use the ElementTree API to read the XML file and then you can use find to find the word you want to replace or use it as an index and then from there you can insert what you need to insert. See links below:
How to update/modify an XML file in python?
https://docs.python.org/2/library/xml.etree.elementtree.html
Post a Comment for "How To Edit An Xml File In Python?"