Read, Modify the xml save it in a new xml using python

4.5k Views Asked by At

Below are the steps I am following:

  1. Reading the xml file as dictionary

    import xmltodict
    
    with open("example.xml") as sxml:
        data = xmltodict.parse(sxml.read())
    
  2. Changing the value

    data["key"]["key1"] = "some value"
    
  3. 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?

2

There are 2 best solutions below

2
On

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.

0
On

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