ElementBuilder.py: friendly syntax for constructing ElementTrees. Inspired by this.



* Extended Element factory

Backward-compatible with the standard ElementTree Element factory with 
the following extensions:

Sub-elements may be supplied as arguments:
    Element('tag', {'a': '5'}, Element('othertag'))

Attribute dictionary is optional:
    Element('tag', Element('othertag'))

Element text may be supplied as an argument:
    Element('tag', 'some text')

Element text and sub-elements:
    Element('tag', 'some text', Element('othertag'))

Element text, sub-elements and sub-element tails:
    Element('tag', 'some text', Element('othertag'), 'tail')


* Namespaces

A namespace is a factory for QNames.

ns.tag == ns+'tag' == QName('http://namespace/uri', 'tag')
where:
ns = Namespace('http://namespace/uri')

A second optional argument to Namespace is prefix which will be used 
when generating XML instead of automatically-generated numeric namespace
prefixes unless it collides with another defined prefix or uri.

Namespace(None) or LocalNamespace generates LocalName objects instead
of QNames but is otherwise similar.

* Callable names

QName and LocalName objects are callable, taking the same arguments as
the Element factory, except the tag argument which is implicitly set to
the QName/LocalName itself.

ns.tag(a='5') == Element(QName('http://namespace/uri', 'tag'), a='5')


* Example

>>> import ElementBuilder
>>> from elementtree import ElementTree
>>> ns = ElementBuilder.Namespace('http://some.uri', 'ns')
>>> e = ns.tag(
...   ns.tag2('content'),
...   ns.tag3(attr='value'),
...   ns.tag4({ns.attr: 'othervalue'}),
...   ns.x(
...     ns.y('y'),
...     ns.z('z'),
...     'some text',
...   )    
... )
>>> ElementTree.dump(e)         # indented for your convenience:
<ns:tag xmlns:ns="http://some.uri">
  <ns:tag2>content</ns:tag2>
  <ns:tag3 attr="value" />
  <ns:tag4 ns:attr="othervalue" />
  <ns:x>
    <ns:y>y</ns:y>
    <ns:z>z</ns:z>some text
  </ns:x>
</ns:tag>


Oren Tirosh

Back

I pretty much agree that XML sucks but in many cases you have to use it anyway. And when that happens, ElementTree makes it a lot more palatable.

"XML combines all the inefficiency of text-based formats with most of the unreadability of binary formats :-)"

    (me, comp.lang.python, 2002)