Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output an XML file using ElementTree in python?

I'm slightly confused about writing an xml file using the xml ElementTree module. I tried to build the document: e.g.

a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')

How do I exactly take this, and write it to a file?

like image 569
Shan Avatar asked Jul 18 '15 17:07

Shan


People also ask

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.

How do you access XML data in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().

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.


1 Answers

Create an instance of ElementTree class and call write():

class xml.etree.ElementTree.ElementTree(element=None, file=None)

ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML.

element is the root element. The tree is initialized with the contents of the XML file if given.

tree = ET.ElementTree(a)
tree.write("output.xml")
like image 70
alecxe Avatar answered Sep 25 '22 01:09

alecxe