5
votes

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?

2

2 Answers

5
votes

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")
2
votes

You can write xml using ElementTree.write() function -

import xml.etree.ElementTree as ET
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
ET.ElementTree(a).write("test.xml")

This would write to file - test.xml -

<a><b /><c><d /></c></a>

To write xml with indents and elements on newline , you can use - xml.dom.minidom.toprettyxml . Example -

import xml.etree.ElementTree as ET
import xml.dom.minidom as md
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
xmlstr = ET.tostring(a).decode()
newxml = md.parse(xmlstr)
newxml = md.parseString(xmlstr)
with open('test.xml','w') as outfile:
    outfile.write(newxml.toprettyxml(indent='\t',newl='\n'))

Now, test.xml would look like -

<?xml version="1.0" ?>
<a>
    <b/>
    <c>
        <d/>
    </c>
</a>