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

2

5

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?

Herniotomy answered 18/7, 2015 at 17:21 Comment(0)
H
5

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")
Heaviness answered 18/7, 2015 at 17:27 Comment(2)
Just to make sure I'm doing this correctly. If I wanted to attach a value or variable to a tag would it be: b.attrib = value , b.tag = variable?Herniotomy
@Herniotomy I think you mean the text of an element. In this case, it should be e.g. d.text = "test".Heaviness
G
2

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>
Grapheme answered 18/7, 2015 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.