Package bitten :: Package util :: Module xmlio :: Class Element

Class Element

object --+    
         |    
  Fragment --+
             |
            Element

Simple XML output generator based on the builder pattern.

Construct XML elements by passing the tag name to the constructor:

>>> print Element('foo')
<foo/>

Attributes can be specified using keyword arguments. The values of the arguments will be converted to strings and any special XML characters escaped:

>>> print Element('foo', bar=42)
<foo bar="42"/>
>>> print Element('foo', bar='1 < 2')
<foo bar="1 &lt; 2"/>
>>> print Element('foo', bar='"baz"')
<foo bar="&quot;baz&quot;"/>

The order in which attributes are rendered is undefined.

Elements can be using item access notation:

>>> print Element('foo')[Element('bar'), Element('baz')]
<foo><bar/><baz/></foo>

Text nodes can be nested in an element by using strings instead of elements in item access. Any special characters in the strings are escaped automatically:

>>> print Element('foo')['Hello world']
<foo>Hello world</foo>
>>> print Element('foo')[42]
<foo>42</foo>
>>> print Element('foo')['1 < 2']
<foo>1 &lt; 2</foo>

This technique also allows mixed content:

>>> print Element('foo')['Hello ', Element('b')['world']]
<foo>Hello <b>world</b></foo>

Finally, text starting with an opening angle bracket is treated specially: under the assumption that the text actually contains XML itself, the whole thing is wrapped in a CDATA block instead of escaping all special characters individually:

>>> print Element('foo')['<bar a="3" b="4"><baz/></bar>']
<foo><![CDATA[<bar a="3" b="4"><baz/></bar>]]></foo>

Valid input are utf-8 or unicode strings, or any type easily converted to unicode such as integers. Output is always utf-8.

Instance Methods
 
__init__(self, name_, **attr)
Create an XML element using the specified tag name.
 
write(self, out, newlines=False)
Serializes the element and writes the XML to the given output stream.

Inherited from Fragment: __getitem__, __str__, append

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __subclasshook__

Properties
  attr
  name

Inherited from Fragment: children

Inherited from object: __class__

Method Details

__init__(self, name_, **attr)
(Constructor)

 

Create an XML element using the specified tag name.

The tag name must be supplied as the first positional argument. All keyword arguments following it are handled as attributes of the element.

Overrides: object.__init__

write(self, out, newlines=False)

 
Serializes the element and writes the XML to the given output stream.
Overrides: Fragment.write