Below are the steps I am following:
Reading the xml file as dictionary
import xmltodict
with open("example.xml") as sxml:
data = xmltodict.parse(sxml.read())
Changing the value
data["key"]["key1"] = "some value"
I want to save the changes in example.xml file or I want to create a new file and save the changes.
How can I do it?
Following README we can simply do
with open('example.xml', 'w') as result_file:
result_file.write(xmltodict.unparse(data))
if you want to overwrite example.xml OR
with open('result.xml', 'w') as result_file:
result_file.write(xmltodict.unparse(data))
if you want to create new file result.xml.
Simple answer:
from lxml import etree
with open('yourxmlfile.xml', encoding='utf8') as inputfile:
contents = inputfile.read()
parser = etree.XMLParser(strip_cdata=False)
tree = etree.XML(contents, parser)
root = tree
#make some edits to root here
with open('yourxmloutput.xml', 'w', encoding='utf8') as outfile:
outfile.write(etree.tostring(root))
docs on the xml module can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With