structa.xml

The structa.xml module provides methods for generating and manipulating XML, primarily in the form of xml.etree.ElementTree objects. The main class of interest is ElementFactory, which can be used to generate entire element-tree documents in a functional manner.

The xml() function can be used in a similar manner to str or repr() to generate XML representations of supported objects (most classes within structa.types support this). Finally, get_transform() can be used to obtain XSLT trees defined by structa (largely for display purposes).

class structa.xml.ElementFactory(namespace=None)[source]

A class inspired by Genshi for easy creation of ElementTree Elements.

The ElementFactory class was inspired by the Genshi builder unit in that it permits simple creation of Elements by calling methods on the tag object named after the element you wish to create. Positional arguments become content within the element, and keyword arguments become attributes.

If you need an attribute or element tag that conflicts with a Python keyword, simply append an underscore to the name (which will be automatically stripped off).

Content can be just about anything, including booleans, integers, longs, dates, times, etc. This class simply applies their default string conversion to them (except basestring derived types like string and unicode which are simply used verbatim).

For example:

>>> tostring(tag.a('A link'))
'<a>A link</a>'
>>> tostring(tag.a('A link', class_='menuitem'))
'<a class="menuitem">A link</a>'
>>> tostring(tag.p('A ', tag.a('link', class_='menuitem')))
'<p>A <a class="menuitem">link</a></p>'
structa.xml.xml(obj)[source]

In a similar manner to str, this function calls the __xml__ method (if any) on obj, returning the result which is expected to be an Element instance representing the object.

structa.xml.get_transform(name)[source]

Return the XSLT transform defined by name in the structa.ui module.

structa.xml.merge_siblings(elem)[source]

Consolidate the content of adjacent sibling child elements with the same tag. For example:

>>> x = XML('<doc><a>a</a><a>b</a><a>c</a><b>d</b><a>e</a></doc>')
>>> tostring(merge_siblings(x))
b'<doc><a>abc</a><b>d</b><a>e</a></doc>'

Note that the function only deals with direct child elements of elem; it does nothing to descendents of those children, even if they have the same tag as their parent:

>>> x = XML('<doc><a>a<a>b</a></a><a>c</a><b>d</b><a>e</a></doc>')
>>> tostring(merge_siblings(x))
b'<doc><a>a<a>b</a>c</a><b>d</b><a>e</a></doc>'