How to output XML file using ElementTree in python?
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.
Elementis the root element. The tree is initialized with the contents of the XML file, if specified.
tree = ET.ElementTree(a)
tree.write("output.xml")
source to share
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>
source to share