3

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?

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
Raswanth
  • 41
  • 1
  • 2
  • Hi! Welcome to StackOverflow! I would suggest you to be more specific in what you need, and also format your code so that it's easier to read for others. See also [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – norok2 Sep 25 '18 at 13:56

2 Answers2

4

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.

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • I am reading both options several times but can not find the difference. Can you give me an hint of difference between OR and NEW variant? – Tib Schott Sep 27 '22 at 13:19
  • @TibSchott: the only difference is in names of files, OP asked about overwriting original file OR creating of a new file – Azat Ibrakov Sep 27 '22 at 13:40
1

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

Community
  • 1
  • 1
Josh Duzan
  • 80
  • 1
  • 8