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>