zzzbbx
zzzbbx

Reputation: 10131

Dump elementtree into xml file

I created an xml tree with something like this

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

how do I dump it into an XML file? I tried top.write(filename), but the method doesn't exist.

Upvotes: 6

Views: 7233

Answers (1)

alecxe
alecxe

Reputation: 473863

You need to instantiate an ElementTree object and call write() method:

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')

The contents of the output.xml after running the code:

<top><child>some text</child></top>

Upvotes: 10

Related Questions