Dump elementtree into xml file
Asked Answered
M

1

6

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.

Madalynmadam answered 15/9, 2014 at 20:56 Comment(1)
Why are you trying to guess the syntax? Have you read the docs?Pontias
C
10

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>
Compelling answered 15/9, 2014 at 20:59 Comment(1)
@Bob: The reason you need an instance of ElementTree is that "This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML." (Italics added.)Hotbox

© 2022 - 2024 — McMap. All rights reserved.