An easy way to write XML in Python

David Mertz's gnosis utilities include the module gnosis.xml.objectify, which makes parsing XML in python as simple as could be.

from gnosis. xml import objectify gnosis.objectify xmltext = """<?xml version="1.0" encoding="UTF-8"?>

<root><first canned="true" yummy="false">spam</first><second>egg</second></root>""" inst = objectify.make_instance(xmltext)

print "first:", inst.first.PCDATA

print " canned:", inst.first.canned

print " yummy:", inst.first.yummy

print "second:", inst.second.PCDATA

Output:

first: spam

canned: true

yummy: false

second: egg

I wanted a similarly simple way to write XML, so I wrote a little module named xmlwriter (zip file) to do it.

Usage:

from xmlwriter import XmlNode, xmlify

from StringIO import StringIO xmlwriterXmlNode, xmlify root = XmlNode(u"root") first = root.first

first.val = u"spam"

first["yummy"] = u"false"

first["canned"] = u"true" root.second.val = u"egg" out = StringIO()

xmlify(root, out)

print out.getvalue()

Output:

<?xml version = "1.0" encoding = "UTF-8" ?>

<root > <first canned = "true" yummy = "false" > spam </first > <second > egg </second > </root >

It's still pretty basic. For example, you can't have sibling nodes with the same tag name. But it's a very simple way to do some down and dirty XML writing.

Here's the xmlwriter module code.