Dump elementtree to xml file

I created an xml tree with something like this

top = Element('top')
child = SubElement(top, 'child')
child.text = 'some text'

How can I dump it into an XML file? I tried top.write(filename), but the method does not exist.

+4
source share
1 answer

You need to create an instance ElementTreeand call write():

import xml.etree.ElementTree as ET

top = ET.Element('top')
child = ET.SubElement(top, 'child')
child.text = 'some text'

tree = ET.ElementTree(top)
tree.write('output.xml')

Content output.xmlafter running the code:

<top><child>some text</child></top>
+8
source

All Articles