Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 515
Bob Avatar asked Sep 15 '14 20:09

Bob


People also ask

How do I write data into an XML file using Python?

Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.

What is XML Etree ElementTree in Python?

The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.

What is an XML data file?

To summarize: An XML file is a file used to store data in the form of hierarchical elements. Data stored in XML files can be read by computer programs with the help of custom tags, which indicate the type of element.


1 Answers

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>
like image 158
alecxe Avatar answered Sep 22 '22 01:09

alecxe