cu.xml: Sleazy XML Utilities For Python

I like XML. The problems it solves are not hard, but using it precludes solving those problems in spectacularly boneheaded ways.

I do not like writing XML. I don't like typing the tag names twice, I don't like the possibility of mismatching closing tags, and I don't like typing all the insipid angle brackets.

It is, of course, possible to use the DOM to generate XML trees, but code using the DOM is rather verbose. For example, generating the following tree:

<parent a="b">

requires the following code, or something like it:

parent = document.createElement('parent')
parent.setAttribute('a', 'b')
for n in xrange(2):
  child = document.createElement('child')

That's just nuts. Printfs would be better.

Enter cu.xml, my sleazy but terse utilities for generating XML:

m = UniveralMaker(document)
parent = m.parent({'a':'b'}, [m.child(str(n)) for n in xrange(2)])


It was inspired by a similar pattern in Javascript: The Definitive Guide by David Flanagan.

I recently discovered that the E-builder from lxml.builder has very similar functionality. Unfortunately, while ElementTree (core, at least) is now standard with Python 2.5, lxml is not.

Here's the Python code. Better yet, there's a version that uses ElementTree. It includes several variations on this theme, plus some utility functions for reading data out of DOM trees, and handy values for generating XHTML in particular. Note the extensive use of __call__ and __getattr__. I warned you it was sleazy.

Last modified 24 December 2013