====================================
Using custom Element classes in lxml
====================================
lxml has very sophisticated support for custom Element classes. You can
provide your own classes for Elements and have lxml use them by default, for
all elements generated by a specific parser or only for a specific tag name in
a specific namespace.
Custom Elements must inherit from the ``lxml.etree.ElementBase`` class, which
provides the Element interface for subclasses::
>>> from lxml import etree
>>> class HonkElement(etree.ElementBase):
... def honking(self):
... return self.get('honking') == 'true'
... honking = property(honking)
This defines a new Element class ``HonkElement`` with a property ``honking``.
Note that you cannot (or rather *must not*) instantiate this class yourself.
lxml.etree will do that for you through its normal ElementTree API.
.. contents::
..
1 Element initialization
2 Setting up a class lookup scheme
2.1 Default class lookup
2.2 Namespace class lookup
2.3 Attribute based lookup
2.4 Custom element class lookup
3 Implementing namespaces
Element initialization
----------------------
There is one thing to know up front. Element classes *must not* have a
constructor, neither must there be any internal state (except for the data
stored in the underlying XML tree). Element instances are created and garbage
collected at need, so there is no way to predict when and how often a
constructor would be called. Even worse, when the ``__init__`` method is
called, the object may not even be initialized yet to represent the XML tag,
so there is not much use in providing an ``__init__`` method in subclasses.
However, there is one possible way to do things on element initialization, if
you really need to. ElementBase classes have an ``_init()`` method that can
be overridden. It can be used to modify the XML tree, e.g. to construct
special children or verify and update attributes.
The semantics of ``_init()`` are as follows:
* It is called at least once on element instantiation time. That is, when a
Python representation of the element is created by lxml. At that time, the
element object is completely initialized to represent a specific XML element
within the tree.
* The method has complete access to the XML tree. Modifications can be done
in exactly the same way as anywhere else in the program.
* Python representations of elements may be created multiple times during the
lifetime of an XML element in the underlying tree. The ``_init()`` code
provided by subclasses must take special care by itself that multiple
executions either are harmless or that they are prevented by some kind of
flag in the XML tree. The latter can be achieved by modifying an attribute
value or by removing or adding a specific child node and then verifying this
before running through the init process.
* Any exceptions raised in ``_init()`` will be propagated throught the API
call that lead to the creation of the Element. So be careful with the code
you write here as its exceptions may turn up in various unexpected places.
Setting up a class lookup scheme
--------------------------------
The first thing to do when deploying custom element classes is to register a
class lookup scheme on a parser. lxml.etree provides quite a number of
different schemes, that also support class lookup based on namespaces or
attribute values. Most lookups support fallback chaining, which allows the
next lookup mechanism to take over when the previous one fails to find a
class.
For example, setting a different default element class for a parser works as
follows::
>>> parser_lookup = etree.ElementDefaultClassLookup(element=HonkElement)
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(parser_lookup)
There is one drawback of the parser based scheme: the ``Element()`` factory
creates a new document that deploys the default parser::
>>> el = etree.Element("root")
>>> print isinstance(el, HonkElement)
False
You should therefore avoid using this function in code that uses custom
classes. The ``makeelement()`` method of parsers provides a simple
replacement::
>>> el = parser.makeelement("root")
>>> print isinstance(el, HonkElement)
True
If you use a parser at the module level, you can easily redirect a module
level ``Element()`` factory to the parser method by adding code like this::
>>> MODULE_PARSER = etree.XMLParser()
>>> Element = MODULE_PARSER.makeelement
While the ``XML()`` and ``HTML()`` factories also depend on the default
parser, you can pass them a different parser as second argument::
>>> element = etree.XML("")
>>> print isinstance(element, HonkElement)
False
>>> element = etree.XML("", parser)
>>> print isinstance(element, HonkElement)
True
Whenever you create a document with a parser, it will inherit the lookup
scheme and all subsequent element instantiations for this document will use
it::
>>> element = etree.fromstring("", parser)
>>> print isinstance(element, HonkElement)
True
>>> el = etree.SubElement(element, "subel")
>>> print isinstance(el, HonkElement)
True
For small projects, you may also consider setting a lookup scheme on the
default parser. To avoid interfering with other modules, however, it is
usually a better idea to use a dedicated parser for each module (or a parser
pool when using threads) and then register the required lookup scheme only for
this parser.
Default class lookup
....................
This is the most simple lookup mechanism. It always returns the default
element class. Consequently, no further fallbacks are supported, but this
scheme is a good fallback for other custom lookup mechanisms.
Usage::
>>> lookup = etree.ElementDefaultClassLookup()
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(lookup)
Note that the default for new parsers is to use the global fallback, which is
also the default lookup (if not configured otherwise).
To change the default element implementation, you can pass your new class to
the constructor. While it accepts classes for ``element``, ``comment`` and
``pi`` nodes, most use cases will only override the element class::
>>> el = parser.makeelement("myelement")
>>> print isinstance(el, HonkElement)
False
>>> lookup = etree.ElementDefaultClassLookup(element=HonkElement)
>>> parser.setElementClassLookup(lookup)
>>> el = parser.makeelement("myelement")
>>> print isinstance(el, HonkElement)
True
>>> el.honking
False
>>> el = parser.makeelement("myelement", honking='true')
>>> print etree.tostring(el)
>>> el.honking
True
Namespace class lookup
......................
This is an advanced lookup mechanism that supports namespace/tag-name specific
element classes. You can select it by calling::
>>> lookup = etree.ElementNamespaceClassLookup()
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(lookup)
See the separate section on `implementing namespaces`_ below to learn how to
make use of it.
.. _`implementing namespaces`: #implementing-namespaces
This scheme supports a fallback mechanism that is used in the case where the
namespace is not found or no class was registered for the element name.
Normally, the default class lookup is used here. To change it, pass the
desired fallback lookup scheme to the constructor::
>>> fallback = etree.ElementDefaultClassLookup(element=HonkElement)
>>> lookup = etree.ElementNamespaceClassLookup(fallback)
>>> parser.setElementClassLookup(lookup)
Attribute based lookup
......................
This scheme uses a mapping from attribute values to classes. An attribute
name is set at initialisation time and is then used to find the corresponding
value. It is set up as follows::
>>> id_class_mapping = {} # maps attribute values to element classes
>>> lookup = etree.AttributeBasedElementClassLookup('id', id_class_mapping)
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(lookup)
Instead of a global setup of this scheme, you should consider using a
per-parser setup.
This class uses its fallback if the attribute is not found or its value is not
in the mapping. Normally, the default class lookup is used here. If you want
to use the namespace lookup, for example, you can use this code::
>>> fallback = etree.ElementNamespaceClassLookup()
>>> lookup = etree.AttributeBasedElementClassLookup(
... 'id', id_class_mapping, fallback)
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(lookup)
Custom element class lookup
...........................
This is the most customisable way of finding element classes. It allows you
to implement a custom lookup scheme in a subclass::
>>> class MyLookup(etree.CustomElementClassLookup):
... def lookup(self, node_type, document, namespace, name):
... return MyElementClass # defined elsewhere
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(MyLookup())
The ``lookup()`` method must either return None (which triggers the fallback
mechanism) or a subclass of ``lxml.etree.ElementBase``. It can take any
decision it wants based on the node type (one of "element", "comment", "PI"),
the XML document of the element, or its namespace or tag name.
Instead of a global setup of this scheme, you should consider using a
per-parser setup.
Implementing namespaces
-----------------------
lxml allows you to implement namespaces, in a rather literal sense. After
setting up the namespace class lookup mechanism as described above, you can
build a new element namespace (or retrieve an existing one) by calling the
Namespace class::
>>> lookup = etree.ElementNamespaceClassLookup()
>>> parser = etree.XMLParser()
>>> parser.setElementClassLookup(lookup)
>>> namespace = etree.Namespace('http://hui.de/honk')
and then register the new element type with that namespace, say, under the tag
name ``honk``::
>>> namespace['honk'] = HonkElement
After this, you create and use your XML elements through the normal API of
lxml::
>>> xml = ''
>>> honk_element = etree.XML(xml, parser)
>>> print honk_element.honking
True
The same works when creating elements by hand::
>>> honk_element = parser.makeelement('{http://hui.de/honk}honk',
... honking='true')
>>> print honk_element.honking
True
Essentially, what this allows you to do, is to give elements a custom API
based on their namespace and tag name.
A somewhat related topic are `extension functions`_ which use a similar
mechanism for registering extension functions in XPath and XSLT.
.. _`extension functions`: extensions.html
In the Namespace example above, we associated the HonkElement class only with
the 'honk' element. If an XML tree contains different elements in the same
namespace, they do not pick up the same implementation::
>>> xml = ''
>>> honk_element = etree.XML(xml, parser)
>>> print honk_element.honking
True
>>> print honk_element[0].honking
Traceback (most recent call last):
...
AttributeError: 'etree._Element' object has no attribute 'honking'
You can therefore provide one implementation per element name in each
namespace and have lxml select the right one on the fly. If you want one
element implementation per namespace (ignoring the element name) or prefer
having a common class for most elements except a few, you can specify a
default implementation for an entire namespace by registering that class with
the empty element name (None).
You may consider following an object oriented approach here. If you build a
class hierarchy of element classes, you can also implement a base class for a
namespace that is used if no specific element class is provided. Again, you
can just pass None as an element name::
>>> class HonkNSElement(etree.ElementBase):
... def honk(self):
... return "HONK"
>>> namespace[None] = HonkNSElement
>>> class HonkElement(HonkNSElement):
... def honking(self):
... return self.get('honking') == 'true'
... honking = property(honking)
>>> namespace['honk'] = HonkElement
Now you can rely on lxml to always return objects of type HonkNSElement or its
subclasses for elements of this namespace::
>>> xml = ''
>>> honk_element = etree.XML(xml, parser)
>>> print type(honk_element), type(honk_element[0])
>>> print honk_element.honking
True
>>> print honk_element.honk()
HONK
>>> print honk_element[0].honk()
HONK
>>> print honk_element[0].honking
Traceback (most recent call last):
...
AttributeError: 'HonkNSElement' object has no attribute 'honking'