Creating XML With Python

Part 1: xml.dom.minidom Basics

There are many resources out there if you'd like to consume and parse XML with Python.  I was looking around the web for resources on producing XML with Python, and I wasn't able to find much.  Here is a pretty simple script and its output.  It will create a WML document.


from xml.dom.minidom import Document
# Create the minidom document doc = Document()
# Create the <wml> base element wml = doc.createElement("wml") doc.appendChild(wml)
# Create the main <card> element maincard = doc.createElement("card") maincard.setAttribute("id", "main") wml.appendChild(maincard)
# Create a <p> element paragraph1 = doc.createElement("p") maincard.appendChild(paragraph1)
# Give the <p> elemenet some text ptext = doc.createTextNode("This is a test!") paragraph1.appendChild(ptext)
# Print our newly created XML print doc.toprettyxml(indent=" ")

(This code was highlighted by Gnu source-highlight.  You can grab a text version here.)  Here's what the above code produces:

<?xml version="1.0" ?>
<wml>
  <card id="main">
    <p>
      This is a test!
    </p>
  </card>
</wml>

As an aside, this XML will probably not parse on a WAP/WML mobile device, as it doesn't have a DOCTYPE.

You can see that creating arbitrary XML with the minidom is nearly trivial.  I didn't say intuitive, I said nearly trivial.  I'm sure that there are better ways of producing XML, but right now the documentation and tutorials are weak at best.  Stay tuned for more.

Links/Resources: