<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" /> <title>Using custom Element classes in lxml</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="document" id="using-custom-element-classes-in-lxml"> <div class="sidemenu"><ul id="lxml"><li><span class="section title">lxml</span><ul class="menu foreign" id="index"><li class="menu title"><a href="index.html">lxml</a><ul class="submenu"><li class="menu item"><a href="index.html#introduction">Introduction</a></li><li class="menu item"><a href="index.html#documentation">Documentation</a></li><li class="menu item"><a href="index.html#download">Download</a></li><li class="menu item"><a href="index.html#mailing-list">Mailing list</a></li><li class="menu item"><a href="index.html#bug-tracker">Bug tracker</a></li><li class="menu item"><a href="index.html#license">License</a></li><li class="menu item"><a href="index.html#old-versions">Old Versions</a></li></ul></li></ul><ul class="menu foreign" id="intro"><li class="menu title"><a href="intro.html">Why lxml?</a><ul class="submenu"><li class="menu item"><a href="intro.html#motto">Motto</a></li><li class="menu item"><a href="intro.html#aims">Aims</a></li></ul></li></ul><ul class="menu foreign" id="installation"><li class="menu title"><a href="installation.html">Installing lxml</a><ul class="submenu"><li class="menu item"><a href="installation.html#requirements">Requirements</a></li><li class="menu item"><a href="installation.html#installation">Installation</a></li><li class="menu item"><a href="installation.html#building-lxml-from-sources">Building lxml from sources</a></li><li class="menu item"><a href="installation.html#ms-windows">MS Windows</a></li><li class="menu item"><a href="installation.html#macos-x">MacOS-X</a></li></ul></li></ul><ul class="menu foreign" id="lxml2"><li class="menu title"><a href="lxml2.html">What's new in lxml 2.0?</a><ul class="submenu"><li class="menu item"><a href="lxml2.html#changes-in-etree-and-objectify">Changes in etree and objectify</a></li><li class="menu item"><a href="lxml2.html#new-modules">New modules</a></li></ul></li></ul><ul class="menu foreign" id="performance"><li class="menu title"><a href="performance.html">Benchmarks and Speed</a><ul class="submenu"><li class="menu item"><a href="performance.html#general-notes">General notes</a></li><li class="menu item"><a href="performance.html#how-to-read-the-timings">How to read the timings</a></li><li class="menu item"><a href="performance.html#parsing-and-serialising">Parsing and Serialising</a></li><li class="menu item"><a href="performance.html#the-elementtree-api">The ElementTree API</a></li><li class="menu item"><a href="performance.html#xpath">XPath</a></li><li class="menu item"><a href="performance.html#a-longer-example">A longer example</a></li><li class="menu item"><a href="performance.html#lxml-objectify">lxml.objectify</a></li></ul></li></ul><ul class="menu foreign" id="compatibility"><li class="menu title"><a href="compatibility.html">ElementTree compatibility of lxml.etree</a></li></ul><ul class="menu foreign" id="FAQ"><li class="menu title"><a href="FAQ.html">lxml FAQ - Frequently Asked Questions</a><ul class="submenu"><li class="menu item"><a href="FAQ.html#general-questions">General Questions</a></li><li class="menu item"><a href="FAQ.html#installation">Installation</a></li><li class="menu item"><a href="FAQ.html#contributing">Contributing</a></li><li class="menu item"><a href="FAQ.html#bugs">Bugs</a></li><li class="menu item"><a href="FAQ.html#threading">Threading</a></li><li class="menu item"><a href="FAQ.html#parsing-and-serialisation">Parsing and Serialisation</a></li><li class="menu item"><a href="FAQ.html#xpath-and-document-traversal">XPath and Document Traversal</a></li></ul></li></ul></li></ul><ul id="Developing with lxml"><li><span class="section title">Developing with lxml</span><ul class="menu foreign" id="tutorial"><li class="menu title"><a href="tutorial.html">The lxml.etree Tutorial</a><ul class="submenu"><li class="menu item"><a href="tutorial.html#the-element-class">The Element class</a></li><li class="menu item"><a href="tutorial.html#the-elementtree-class">The ElementTree class</a></li><li class="menu item"><a href="tutorial.html#parsing-from-strings-and-files">Parsing from strings and files</a></li><li class="menu item"><a href="tutorial.html#namespaces">Namespaces</a></li><li class="menu item"><a href="tutorial.html#the-e-factory">The E-factory</a></li><li class="menu item"><a href="tutorial.html#elementpath">ElementPath</a></li></ul></li></ul><ul class="menu foreign" id="api index"><li class="menu title"><a href="api/index.html">API reference</a></li></ul><ul class="menu foreign" id="api"><li class="menu title"><a href="api.html">APIs specific to lxml.etree</a><ul class="submenu"><li class="menu item"><a href="api.html#lxml-etree">lxml.etree</a></li><li class="menu item"><a href="api.html#other-element-apis">Other Element APIs</a></li><li class="menu item"><a href="api.html#trees-and-documents">Trees and Documents</a></li><li class="menu item"><a href="api.html#iteration">Iteration</a></li><li class="menu item"><a href="api.html#error-handling-on-exceptions">Error handling on exceptions</a></li><li class="menu item"><a href="api.html#error-logging">Error logging</a></li><li class="menu item"><a href="api.html#serialisation">Serialisation</a></li><li class="menu item"><a href="api.html#xinclude-and-elementinclude">XInclude and ElementInclude</a></li><li class="menu item"><a href="api.html#write-c14n-on-elementtree">write_c14n on ElementTree</a></li></ul></li></ul><ul class="menu foreign" id="parsing"><li class="menu title"><a href="parsing.html">Parsing XML and HTML with lxml</a><ul class="submenu"><li class="menu item"><a href="parsing.html#parsers">Parsers</a></li><li class="menu item"><a href="parsing.html#the-target-parser-interface">The target parser interface</a></li><li class="menu item"><a href="parsing.html#the-feed-parser-interface">The feed parser interface</a></li><li class="menu item"><a href="parsing.html#iterparse-and-iterwalk">iterparse and iterwalk</a></li><li class="menu item"><a href="parsing.html#python-unicode-strings">Python unicode strings</a></li></ul></li></ul><ul class="menu foreign" id="validation"><li class="menu title"><a href="validation.html">Validation with lxml</a><ul class="submenu"><li class="menu item"><a href="validation.html#validation-at-parse-time">Validation at parse time</a></li><li class="menu item"><a href="validation.html#dtd">DTD</a></li><li class="menu item"><a href="validation.html#relaxng">RelaxNG</a></li><li class="menu item"><a href="validation.html#xmlschema">XMLSchema</a></li><li class="menu item"><a href="validation.html#schematron">Schematron</a></li></ul></li></ul><ul class="menu foreign" id="xpathxslt"><li class="menu title"><a href="xpathxslt.html">XPath and XSLT with lxml</a><ul class="submenu"><li class="menu item"><a href="xpathxslt.html#xpath">XPath</a></li><li class="menu item"><a href="xpathxslt.html#xslt">XSLT</a></li></ul></li></ul><ul class="menu foreign" id="objectify"><li class="menu title"><a href="objectify.html">lxml.objectify</a><ul class="submenu"><li class="menu item"><a href="objectify.html#the-lxml-objectify-api">The lxml.objectify API</a></li><li class="menu item"><a href="objectify.html#asserting-a-schema">Asserting a Schema</a></li><li class="menu item"><a href="objectify.html#objectpath">ObjectPath</a></li><li class="menu item"><a href="objectify.html#python-data-types">Python data types</a></li><li class="menu item"><a href="objectify.html#how-data-types-are-matched">How data types are matched</a></li><li class="menu item"><a href="objectify.html#what-is-different-from-lxml-etree?">What is different from lxml.etree?</a></li></ul></li></ul><ul class="menu foreign" id="lxmlhtml"><li class="menu title"><a href="lxmlhtml.html">lxml.html</a><ul class="submenu"><li class="menu item"><a href="lxmlhtml.html#parsing-html">Parsing HTML</a></li><li class="menu item"><a href="lxmlhtml.html#html-element-methods">HTML Element Methods</a></li><li class="menu item"><a href="lxmlhtml.html#running-html-doctests">Running HTML doctests</a></li><li class="menu item"><a href="lxmlhtml.html#creating-html-with-the-e-factory">Creating HTML with the E-factory</a></li><li class="menu item"><a href="lxmlhtml.html#working-with-links">Working with links</a></li><li class="menu item"><a href="lxmlhtml.html#forms">Forms</a></li><li class="menu item"><a href="lxmlhtml.html#cleaning-up-html">Cleaning up HTML</a></li><li class="menu item"><a href="lxmlhtml.html#html-diff">HTML Diff</a></li><li class="menu item"><a href="lxmlhtml.html#examples">Examples</a></li></ul></li></ul><ul class="menu foreign" id="cssselect"><li class="menu title"><a href="cssselect.html">lxml.cssselect</a><ul class="submenu"><li class="menu item"><a href="cssselect.html#the-cssselector-class">The CSSSelector class</a></li><li class="menu item"><a href="cssselect.html#css-selectors">CSS Selectors</a></li><li class="menu item"><a href="cssselect.html#limitations">Limitations</a></li></ul></li></ul><ul class="menu foreign" id="elementsoup"><li class="menu title"><a href="elementsoup.html">BeautifulSoup Parser</a><ul class="submenu"><li class="menu item"><a href="elementsoup.html#entity-handling">Entity handling</a></li><li class="menu item"><a href="elementsoup.html#using-soupparser-as-a-fallback">Using soupparser as a fallback</a></li></ul></li></ul></li></ul><ul id="Extending lxml"><li><span class="section title">Extending lxml</span><ul class="menu foreign" id="resolvers"><li class="menu title"><a href="resolvers.html">Document loading and URL resolving</a><ul class="submenu"><li class="menu item"><a href="resolvers.html#resolvers">Resolvers</a></li><li class="menu item"><a href="resolvers.html#document-loading-in-context">Document loading in context</a></li><li class="menu item"><a href="resolvers.html#i-o-access-control-in-xslt">I/O access control in XSLT</a></li></ul></li></ul><ul class="menu foreign" id="extensions"><li class="menu title"><a href="extensions.html">Extension functions for XPath and XSLT</a><ul class="submenu"><li class="menu item"><a href="extensions.html#the-functionnamespace">The FunctionNamespace</a></li><li class="menu item"><a href="extensions.html#global-prefix-assignment">Global prefix assignment</a></li><li class="menu item"><a href="extensions.html#the-xpath-context">The XPath context</a></li><li class="menu item"><a href="extensions.html#evaluators-and-xslt">Evaluators and XSLT</a></li><li class="menu item"><a href="extensions.html#evaluator-local-extensions">Evaluator-local extensions</a></li><li class="menu item"><a href="extensions.html#what-to-return-from-a-function">What to return from a function</a></li></ul></li></ul><ul class="menu current" id="element classes"><li class="menu title"><a href="element_classes.html">Using custom Element classes in lxml</a><ul class="submenu"><li class="menu item"><a href="element_classes.html#element-initialization">Element initialization</a></li><li class="menu item"><a href="element_classes.html#setting-up-a-class-lookup-scheme">Setting up a class lookup scheme</a></li><li class="menu item"><a href="element_classes.html#implementing-namespaces">Implementing namespaces</a></li></ul></li></ul><ul class="menu foreign" id="sax"><li class="menu title"><a href="sax.html">Sax support</a><ul class="submenu"><li class="menu item"><a href="sax.html#building-a-tree-from-sax-events">Building a tree from SAX events</a></li><li class="menu item"><a href="sax.html#producing-sax-events-from-an-elementtree-or-element">Producing SAX events from an ElementTree or Element</a></li><li class="menu item"><a href="sax.html#interfacing-with-pulldom-minidom">Interfacing with pulldom/minidom</a></li></ul></li></ul><ul class="menu foreign" id="capi"><li class="menu title"><a href="capi.html">The public C-API of lxml.etree</a><ul class="submenu"><li class="menu item"><a href="capi.html#writing-external-modules-in-cython">Writing external modules in Cython</a></li><li class="menu item"><a href="capi.html#writing-external-modules-in-c">Writing external modules in C</a></li></ul></li></ul></li></ul><ul id="Developing lxml"><li><span class="section title">Developing lxml</span><ul class="menu foreign" id="build"><li class="menu title"><a href="build.html">How to build lxml from source</a><ul class="submenu"><li class="menu item"><a href="build.html#cython">Cython</a></li><li class="menu item"><a href="build.html#subversion">Subversion</a></li><li class="menu item"><a href="build.html#setuptools">Setuptools</a></li><li class="menu item"><a href="build.html#running-the-tests-and-reporting-errors">Running the tests and reporting errors</a></li><li class="menu item"><a href="build.html#contributing-an-egg">Contributing an egg</a></li><li class="menu item"><a href="build.html#providing-newer-library-versions-on-mac-os-x">Providing newer library versions on Mac-OS X</a></li><li class="menu item"><a href="build.html#static-linking-on-windows">Static linking on Windows</a></li><li class="menu item"><a href="build.html#building-debian-packages-from-svn-sources">Building Debian packages from SVN sources</a></li></ul></li></ul><ul class="menu foreign" id="lxml source howto"><li class="menu title"><a href="lxml-source-howto.html">How to read the source of lxml</a><ul class="submenu"><li class="menu item"><a href="lxml-source-howto.html#what-is-cython?">What is Cython?</a></li><li class="menu item"><a href="lxml-source-howto.html#where-to-start?">Where to start?</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-etree">lxml.etree</a></li><li class="menu item"><a href="lxml-source-howto.html#python-modules">Python modules</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-objectify">lxml.objectify</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-pyclasslookup">lxml.pyclasslookup</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-html">lxml.html</a></li></ul></li></ul><ul class="menu foreign" id="changes 2 0 11"><li class="menu title"><a href="changes-2.0.11.html">Release Changelog</a></li></ul><ul class="menu foreign" id="credits"><li class="menu title"><a href="credits.html">Credits</a><ul class="submenu"><li class="menu item"><a href="credits.html#special-thanks-goes-to:">Special thanks goes to:</a></li></ul></li></ul></li></ul></div><h1 class="title">Using custom Element classes in lxml</h1> <p>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, for a specific tag name in a specific namespace or for an exact element at a specific position in the tree.</p> <p>Custom Elements must inherit from the <tt class="docutils literal"><span class="pre">lxml.etree.ElementBase</span></tt> class, which provides the Element interface for subclasses:</p> <pre class="literal-block"> >>> from lxml import etree >>> class HonkElement(etree.ElementBase): ... def honking(self): ... return self.get('honking') == 'true' ... honking = property(honking) </pre> <p>This defines a new Element class <tt class="docutils literal"><span class="pre">HonkElement</span></tt> with a property <tt class="docutils literal"><span class="pre">honking</span></tt>.</p> <p>Note that you cannot (or rather <em>must not</em>) instantiate this class yourself. lxml.etree will do that for you through its normal ElementTree API.</p> <div class="contents topic"> <p class="topic-title first"><a id="contents" name="contents">Contents</a></p> <ul class="simple"> <li><a class="reference" href="#element-initialization" id="id2" name="id2">Element initialization</a></li> <li><a class="reference" href="#setting-up-a-class-lookup-scheme" id="id3" name="id3">Setting up a class lookup scheme</a><ul> <li><a class="reference" href="#default-class-lookup" id="id4" name="id4">Default class lookup</a></li> <li><a class="reference" href="#namespace-class-lookup" id="id5" name="id5">Namespace class lookup</a></li> <li><a class="reference" href="#attribute-based-lookup" id="id6" name="id6">Attribute based lookup</a></li> <li><a class="reference" href="#custom-element-class-lookup" id="id7" name="id7">Custom element class lookup</a></li> <li><a class="reference" href="#tree-based-element-class-lookup-in-python" id="id8" name="id8">Tree based element class lookup in Python</a></li> </ul> </li> <li><a class="reference" href="#id1" id="id9" name="id9">Implementing namespaces</a></li> </ul> </div> <div class="section"> <h1><a id="element-initialization" name="element-initialization">Element initialization</a></h1> <p>There is one thing to know up front. Element classes <em>must not</em> 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 <tt class="docutils literal"><span class="pre">__init__</span></tt> 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 <tt class="docutils literal"><span class="pre">__init__</span></tt> method in subclasses.</p> <p>Most use cases will not require any class initialisation, so you can content yourself with skipping to the next section for now. However, if you really need to set up your element class on instantiation, there is one possible way to do so. ElementBase classes have an <tt class="docutils literal"><span class="pre">_init()</span></tt> 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.</p> <p>The semantics of <tt class="docutils literal"><span class="pre">_init()</span></tt> are as follows:</p> <ul class="simple"> <li>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.</li> <li>The method has complete access to the XML tree. Modifications can be done in exactly the same way as anywhere else in the program.</li> <li>Python representations of elements may be created multiple times during the lifetime of an XML element in the underlying tree. The <tt class="docutils literal"><span class="pre">_init()</span></tt> 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.</li> <li>Any exceptions raised in <tt class="docutils literal"><span class="pre">_init()</span></tt> 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.</li> </ul> </div> <div class="section"> <h1><a id="setting-up-a-class-lookup-scheme" name="setting-up-a-class-lookup-scheme">Setting up a class lookup scheme</a></h1> <p>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.</p> <p>For example, setting a different default element class for a parser works as follows:</p> <pre class="literal-block"> >>> parser_lookup = etree.ElementDefaultClassLookup(element=HonkElement) >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(parser_lookup) </pre> <p>There is one drawback of the parser based scheme: the <tt class="docutils literal"><span class="pre">Element()</span></tt> factory does not know about your specialised parser and creates a new document that deploys the default parser:</p> <pre class="literal-block"> >>> el = etree.Element("root") >>> print isinstance(el, HonkElement) False </pre> <p>You should therefore avoid using this function in code that uses custom classes. The <tt class="docutils literal"><span class="pre">makeelement()</span></tt> method of parsers provides a simple replacement:</p> <pre class="literal-block"> >>> el = parser.makeelement("root") >>> print isinstance(el, HonkElement) True </pre> <p>If you use a parser at the module level, you can easily redirect a module level <tt class="docutils literal"><span class="pre">Element()</span></tt> factory to the parser method by adding code like this:</p> <pre class="literal-block"> >>> MODULE_PARSER = etree.XMLParser() >>> Element = MODULE_PARSER.makeelement </pre> <p>While the <tt class="docutils literal"><span class="pre">XML()</span></tt> and <tt class="docutils literal"><span class="pre">HTML()</span></tt> factories also depend on the default parser, you can pass them a different parser as second argument:</p> <pre class="literal-block"> >>> element = etree.XML("<test/>") >>> print isinstance(element, HonkElement) False >>> element = etree.XML("<test/>", parser) >>> print isinstance(element, HonkElement) True </pre> <p>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:</p> <pre class="literal-block"> >>> element = etree.fromstring("<test/>", parser) >>> print isinstance(element, HonkElement) True >>> el = etree.SubElement(element, "subel") >>> print isinstance(el, HonkElement) True </pre> <p>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.</p> <div class="section"> <h2><a id="default-class-lookup" name="default-class-lookup">Default class lookup</a></h2> <p>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.</p> <p>Usage:</p> <pre class="literal-block"> >>> lookup = etree.ElementDefaultClassLookup() >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(lookup) </pre> <p>Note that the default for new parsers is to use the global fallback, which is also the default lookup (if not configured otherwise).</p> <p>To change the default element implementation, you can pass your new class to the constructor. While it accepts classes for <tt class="docutils literal"><span class="pre">element</span></tt>, <tt class="docutils literal"><span class="pre">comment</span></tt> and <tt class="docutils literal"><span class="pre">pi</span></tt> nodes, most use cases will only override the element class:</p> <pre class="literal-block"> >>> el = parser.makeelement("myelement") >>> print isinstance(el, HonkElement) False >>> lookup = etree.ElementDefaultClassLookup(element=HonkElement) >>> parser.set_element_class_lookup(lookup) >>> el = parser.makeelement("myelement") >>> print isinstance(el, HonkElement) True >>> el.honking False >>> el = parser.makeelement("myelement", honking='true') >>> print etree.tostring(el) <myelement honking="true"/> >>> el.honking True </pre> </div> <div class="section"> <h2><a id="namespace-class-lookup" name="namespace-class-lookup">Namespace class lookup</a></h2> <p>This is an advanced lookup mechanism that supports namespace/tag-name specific element classes. You can select it by calling:</p> <pre class="literal-block"> >>> lookup = etree.ElementNamespaceClassLookup() >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(lookup) </pre> <p>See the separate section on <a class="reference" href="#implementing-namespaces">implementing namespaces</a> below to learn how to make use of it.</p> <p>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:</p> <pre class="literal-block"> >>> fallback = etree.ElementDefaultClassLookup(element=HonkElement) >>> lookup = etree.ElementNamespaceClassLookup(fallback) >>> parser.set_element_class_lookup(lookup) </pre> </div> <div class="section"> <h2><a id="attribute-based-lookup" name="attribute-based-lookup">Attribute based lookup</a></h2> <p>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:</p> <pre class="literal-block"> >>> id_class_mapping = {} # maps attribute values to element classes >>> lookup = etree.AttributeBasedElementClassLookup( ... 'id', id_class_mapping) >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(lookup) </pre> <p>Instead of a global setup of this scheme, you should consider using a per-parser setup.</p> <p>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:</p> <pre class="literal-block"> >>> fallback = etree.ElementNamespaceClassLookup() >>> lookup = etree.AttributeBasedElementClassLookup( ... 'id', id_class_mapping, fallback) >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(lookup) </pre> </div> <div class="section"> <h2><a id="custom-element-class-lookup" name="custom-element-class-lookup">Custom element class lookup</a></h2> <p>This is the most customisable way of finding element classes on a per-element basis. It allows you to implement a custom lookup scheme in a subclass:</p> <pre class="literal-block"> >>> class MyLookup(etree.CustomElementClassLookup): ... def lookup(self, node_type, document, namespace, name): ... return MyElementClass # defined elsewhere >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(MyLookup()) </pre> <p>The <tt class="docutils literal"><span class="pre">lookup()</span></tt> method must either return None (which triggers the fallback mechanism) or a subclass of <tt class="docutils literal"><span class="pre">lxml.etree.ElementBase</span></tt>. 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.</p> <p>Instead of a global setup of this scheme, you should consider using a per-parser setup.</p> </div> <div class="section"> <h2><a id="tree-based-element-class-lookup-in-python" name="tree-based-element-class-lookup-in-python">Tree based element class lookup in Python</a></h2> <p>Taking more elaborate decisions than allowed by the custom scheme is difficult to achieve in pure Python. It would require access to the tree - before the elements in the tree have been instantiated as Python Element objects.</p> <p>Luckily, there is a way to do this. The separate module <tt class="docutils literal"><span class="pre">lxml.pyclasslookup</span></tt> provides a lookup class called <tt class="docutils literal"><span class="pre">PythonElementClassLookup</span></tt> that works similar to the custom lookup scheme:</p> <pre class="literal-block"> >>> from lxml.pyclasslookup import PythonElementClassLookup >>> class MyLookup(PythonElementClassLookup): ... def lookup(self, document, element): ... return MyElementClass # defined elsewhere >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(MyLookup()) </pre> <p>As before, the first argument to the <tt class="docutils literal"><span class="pre">lookup()</span></tt> method is the opaque document instance that contains the Element. The second arguments is a lightweight Element proxy implementation that is only valid during the lookup. Do not try to keep a reference to it. Once the lookup is finished, the proxy will become invalid. You will get an <tt class="docutils literal"><span class="pre">AssertionError</span></tt> if you access any of the properties or methods outside the scope of the lookup call where they were instantiated.</p> <p>During the lookup, the element object behaves mostly like a normal Element instance. It provides the properties <tt class="docutils literal"><span class="pre">tag</span></tt>, <tt class="docutils literal"><span class="pre">text</span></tt>, <tt class="docutils literal"><span class="pre">tail</span></tt> etc. and supports indexing, slicing and the <tt class="docutils literal"><span class="pre">getchildren()</span></tt>, <tt class="docutils literal"><span class="pre">getparent()</span></tt> etc. methods. It does <em>not</em> support iteration, nor does it support any kind of modification. All of its properties are read-only and it cannot be removed or inserted into other trees. You can use it as a starting point to freely traverse the tree and collect any kind of information that its elements provide. Once you have taken the decision which class to use for this element, you can simply return it and have lxml take care of cleaning up the instantiated proxy classes.</p> </div> </div> <div class="section"> <h1><a id="id1" name="id1">Implementing namespaces</a></h1> <p>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 <tt class="docutils literal"><span class="pre">get_namespace(uri)</span></tt> method of the lookup:</p> <pre class="literal-block"> >>> lookup = etree.ElementNamespaceClassLookup() >>> parser = etree.XMLParser() >>> parser.set_element_class_lookup(lookup) >>> namespace = lookup.get_namespace('http://hui.de/honk') </pre> <p>and then register the new element type with that namespace, say, under the tag name <tt class="docutils literal"><span class="pre">honk</span></tt>:</p> <pre class="literal-block"> >>> namespace['honk'] = HonkElement </pre> <p>After this, you create and use your XML elements through the normal API of lxml:</p> <pre class="literal-block"> >>> xml = '<honk xmlns="http://hui.de/honk" honking="true"/>' >>> honk_element = etree.XML(xml, parser) >>> print honk_element.honking True </pre> <p>The same works when creating elements by hand:</p> <pre class="literal-block"> >>> honk_element = parser.makeelement('{http://hui.de/honk}honk', ... honking='true') >>> print honk_element.honking True </pre> <p>Essentially, what this allows you to do, is to give elements a custom API based on their namespace and tag name.</p> <p>A somewhat related topic are <a class="reference" href="extensions.html">extension functions</a> which use a similar mechanism for registering extension functions in XPath and XSLT.</p> <p>In the setup 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:</p> <pre class="literal-block"> >>> xml = '<honk xmlns="http://hui.de/honk" honking="true"><bla/></honk>' >>> honk_element = etree.XML(xml, parser) >>> print honk_element.honking True >>> print honk_element[0].honking Traceback (most recent call last): ... AttributeError: 'lxml.etree._Element' object has no attribute 'honking' </pre> <p>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).</p> <p>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:</p> <pre class="literal-block"> >>> 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 </pre> <p>Now you can rely on lxml to always return objects of type HonkNSElement or its subclasses for elements of this namespace:</p> <pre class="literal-block"> >>> xml = '<honk xmlns="http://hui.de/honk" honking="true"><bla/></honk>' >>> honk_element = etree.XML(xml, parser) >>> print type(honk_element), type(honk_element[0]) <class 'HonkElement'> <class 'HonkNSElement'> >>> 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' </pre> </div> </div> <div class="footer"> <hr class="footer" /> Generated on: 2008-12-12. </div> </body> </html>