[UPDATED] Finally xml.dom.minidom sucks balls, it can burn up to hundreds/gigs of megabytes of sweet memory when working with “large” xml files (10 Mb or more). See this post for a really lightweight implementation.
Howdy,
Here is a quick reference of how to create an XML document and output it in Python.
import xml.dom.minidom # create the document doc = xml.dom.minidom.Document() # populate it with an element root = doc.createElement("teabag") doc.appendChild(root) # time to give some children to the root element, one with an attribute for instance child1 = doc.createElement("spam") child1.setAttribute("name", "value") root.appendChild(child1) # and another one with some text child2 = doc.createElement("eggs") text = doc.createTextNode("spam and eggs!") child2.appendChild(text) root.appendChild(child2) # let's get the output, as a string print doc.toprettyxml() # you're supposed to get the following output: #<?xml version="1.0" ?> #<teabag> # <spam name="value"/> # <eggs> # spam and eggs! # </eggs> #</teabag>
How nice is that ? Yep, a lot.