How to output XML file using ElementTree in python?

I am a little confused about writing xml file using xml ElementTree module. I tried to create a document: for example

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

      

How can I do this and write to a file?

+3


source to share


2 answers


Create an instance of the class ElementTree

and call write()

:

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

The wrapper class ElementTree. This class is a whole element of the hierarchy and adds additional support for serializing to and from standard XML.

Element

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



tree = ET.ElementTree(a)
tree.write("output.xml")

      

+2


source


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 will write to a file - test.xml

-

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

      




To write xml with indentation and elements on a new line, 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'))

      

It test.xml

will now look like

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

      

+2


source







All Articles