Category: Code
Date: 2008.02.09

Creating XML with Python using xml.dom.minidom

A google search for "create xml with python" doesn't return the python documentation site as top link. Searching for "site:www.python.org create xml with python" doesn't do much better. Google does lead to a few good pages on the topic. I read those to start.

Create a document:

    import xml.dom.minidom
    doc = xml.dom.minidom.Document()

Create an element:

    el = doc.createElementNS("http://example.com/namespaceURI", "name")
    doc.appendChild(el)

Don't to be fooled in to thinking minidom's output methods will serialize that namespace in any way whatsoever. Long discussions debate this point... I didn't go off and read the DOM spec. (Well, okay, I peeked.) I added my own namespace attributes, setting the default namespace in this example. The first time I felt let down by python.

    el.setAttribute("xmlns", "http://example.com/namespaceURI")

Create additional elements and text nodes.

    elWithContent = doc.createElementNS("http://example.com/namespaceURI", "content")
    content = doc.createTextNode("some text content")
    elWithContent.appendChild(content)
    el.appendChild(elWithContent)

Serialize to a file.

    fileObj = open("example.xml", 'w')
    fileObj.write(doc.toxml())
    fileObj.close()

The resulting output:

    <name xmlns="http://example.com/namespaceURI"><content>some text content</content></name>