0

The content of code

import xml.etree.ElementTree as etree
import sys
tree = etree.parse('in.xml')
out = open('out.xml','w')
out.write(etree.dump(tree))
out.close()

However, once I run it, i get empty content on out.xml.

Any idea on how to fix this?

Regards, Ashish

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
Ashish
  • 27
  • 4
  • Use `tree.write()` as it says here: https://stackoverflow.com/a/39338941/407651. `dump()` should be used for debugging only: https://docs.python.org/3/library/xml.etree.elementtree.html?highlight=elementtree#xml.etree.ElementTree.dump. – mzjn Jun 26 '22 at 17:25
  • 1
    Does this answer your question? [ElementTree Write to an XML](https://stackoverflow.com/questions/39338733/elementtree-write-to-an-xml) – mzjn Jun 26 '22 at 17:29
  • Thanks! After changing the code as below, it's working fine. import xml.etree.ElementTree as etree import sys tree = etree.parse('in1.xml') out = open('out.xml','w') root=tree.getroot() y=etree.tostring(root, encoding='utf8').decode('utf8') out.write(y) out.close() – Ashish Jun 26 '22 at 20:00

1 Answers1

0

After changing the code as below, it's working fine.

import xml.etree.ElementTree as etree
import sys
tree = etree.parse('in1.xml')
out = open('out.xml','w')
root=tree.getroot()
y=etree.tostring(root, encoding='utf8').decode('utf8')
out.write(y)
out.close()
Ashish
  • 27
  • 4
  • 1
    Why don't you just use `tree.write()`? There is no need for `out = open('out.xml','w')`. – mzjn Jun 27 '22 at 05:55