1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" />
6 <title>Using custom Element classes in lxml</title>
7 <link rel="stylesheet" href="style.css" type="text/css" />
10 <div class="document" id="using-custom-element-classes-in-lxml">
11 <div class="sidemenu"><ul id="lxml-section"><li><span class="section title">lxml</span><ul class="menu foreign" id="index-menu"><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#support-the-project">Support the project</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><li class="menu item"><a href="index.html#legal-notice-for-donations">Legal Notice for Donations</a></li></ul></li></ul><ul class="menu foreign" id="intro-menu"><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-menu"><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#using-lxml-with-python-libxml2">Using lxml with python-libxml2</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="performance-menu"><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-menu"><li class="menu title"><a href="compatibility.html">ElementTree compatibility of lxml.etree</a></li></ul><ul class="menu foreign" id="FAQ-menu"><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#id1">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-section"><li><span class="section title">Developing with lxml</span><ul class="menu foreign" id="tutorial-menu"><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-menu"><li class="menu title"><a href="api/index.html">API reference</a></li></ul><ul class="menu foreign" id="api-menu"><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#cdata">CDATA</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-menu"><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-menu"><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#id1">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#id2">Schematron</a></li><li class="menu item"><a href="validation.html#id3">(Pre-ISO-Schematron)</a></li></ul></li></ul><ul class="menu foreign" id="xpathxslt-menu"><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-menu"><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-menu"><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-menu"><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#namespaces">Namespaces</a></li><li class="menu item"><a href="cssselect.html#limitations">Limitations</a></li></ul></li></ul><ul class="menu foreign" id="elementsoup-menu"><li class="menu title"><a href="elementsoup.html">BeautifulSoup Parser</a><ul class="submenu"><li class="menu item"><a href="elementsoup.html#parsing-with-the-soupparser">Parsing with the soupparser</a></li><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><li class="menu item"><a href="elementsoup.html#using-only-the-encoding-detection">Using only the encoding detection</a></li></ul></li></ul><ul class="menu foreign" id="html5parser-menu"><li class="menu title"><a href="html5parser.html">html5lib Parser</a><ul class="submenu"><li class="menu item"><a href="html5parser.html#differences-to-regular-html-parsing">Differences to regular HTML parsing</a></li><li class="menu item"><a href="html5parser.html#function-reference">Function Reference</a></li></ul></li></ul></li></ul><ul id="Extending lxml-section"><li><span class="section title">Extending lxml</span><ul class="menu foreign" id="resolvers-menu"><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#xml-catalogs">XML Catalogs</a></li><li class="menu item"><a href="resolvers.html#uri-resolvers">URI 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-menu"><li class="menu title"><a href="extensions.html">Python extensions for XPath and XSLT</a><ul class="submenu"><li class="menu item"><a href="extensions.html#xpath-extension-functions">XPath Extension functions</a></li><li class="menu item"><a href="extensions.html#xslt-extension-elements">XSLT extension elements</a></li></ul></li></ul><ul class="menu current" id="element classes-menu"><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#background-on-element-proxies">Background on Element proxies</a></li><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#generating-xml-with-custom-classes">Generating XML with custom classes</a></li><li class="menu item"><a href="element_classes.html#id1">Implementing namespaces</a></li></ul></li></ul><ul class="menu foreign" id="sax-menu"><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-menu"><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-section"><li><span class="section title">Developing lxml</span><ul class="menu foreign" id="build-menu"><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#github-git-and-hg">Github, git and hg</a></li><li class="menu item"><a href="build.html#id2">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#building-an-egg">Building an egg</a></li><li class="menu item"><a href="build.html#building-lxml-on-macos-x">Building lxml on MacOS-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-menu"><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-html">lxml.html</a></li></ul></li></ul><ul class="menu foreign" id="changes 2 3 5-menu"><li class="menu title"><a href="changes-2.3.5.html">Release Changelog</a></li></ul><ul class="menu foreign" id="credits-menu"><li class="menu title"><a href="credits.html">Credits</a><ul class="submenu"><li class="menu item"><a href="credits.html#main-contributors">Main contributors</a></li><li class="menu item"><a href="credits.html#special-thanks-goes-to">Special thanks goes to:</a></li></ul></li></ul></li><li><a href="http://lxml.de/sitemap.html">Sitemap</a></li></ul></div><h1 class="title">Using custom Element classes in lxml</h1>
13 <p>lxml has very sophisticated support for custom Element classes. You
14 can provide your own classes for Elements and have lxml use them by
15 default for all elements generated by a specific parser, only for a
16 specific tag name in a specific namespace or even for an exact element
17 at a specific position in the tree.</p>
18 <p>Custom Elements must inherit from the <tt class="docutils literal">lxml.etree.ElementBase</tt> class, which
19 provides the Element interface for subclasses:</p>
20 <div class="syntax"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">lxml</span> <span class="kn">import</span> <span class="n">etree</span>
22 <span class="gp">>>> </span><span class="k">class</span> <span class="nc">honk</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">ElementBase</span><span class="p">):</span>
23 <span class="gp">... </span> <span class="nd">@property</span>
24 <span class="gp">... </span> <span class="k">def</span> <span class="nf">honking</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
25 <span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'honking'</span><span class="p">)</span> <span class="o">==</span> <span class="s">'true'</span>
27 <p>This defines a new Element class <tt class="docutils literal">honk</tt> with a property <tt class="docutils literal">honking</tt>.</p>
28 <p>The following document describes how you can make lxml.etree use these
29 custom Element classes.</p>
30 <div class="contents topic" id="contents">
31 <p class="topic-title first">Contents</p>
33 <li><a class="reference internal" href="#background-on-element-proxies" id="id2">Background on Element proxies</a></li>
34 <li><a class="reference internal" href="#element-initialization" id="id3">Element initialization</a></li>
35 <li><a class="reference internal" href="#setting-up-a-class-lookup-scheme" id="id4">Setting up a class lookup scheme</a><ul>
36 <li><a class="reference internal" href="#default-class-lookup" id="id5">Default class lookup</a></li>
37 <li><a class="reference internal" href="#namespace-class-lookup" id="id6">Namespace class lookup</a></li>
38 <li><a class="reference internal" href="#attribute-based-lookup" id="id7">Attribute based lookup</a></li>
39 <li><a class="reference internal" href="#custom-element-class-lookup" id="id8">Custom element class lookup</a></li>
40 <li><a class="reference internal" href="#tree-based-element-class-lookup-in-python" id="id9">Tree based element class lookup in Python</a></li>
43 <li><a class="reference internal" href="#generating-xml-with-custom-classes" id="id10">Generating XML with custom classes</a></li>
44 <li><a class="reference internal" href="#id1" id="id11">Implementing namespaces</a></li>
47 <div class="section" id="background-on-element-proxies">
48 <h1>Background on Element proxies</h1>
49 <p>Being based on libxml2, lxml.etree holds the entire XML tree in a C
50 structure. To communicate with Python code, it creates Python proxy
51 objects for the XML elements on demand.</p>
53 <img alt="proxies.png" src="proxies.png" />
55 <p>The mapping between C elements and Python Element classes is
56 completely configurable. When you ask lxml.etree for an Element by
57 using its API, it will instantiate your classes for you. All you have
58 to do is tell lxml which class to use for which kind of Element. This
59 is done through a class lookup scheme, as described in the sections
62 <div class="section" id="element-initialization">
63 <h1>Element initialization</h1>
64 <p>There is one thing to know up front. Element classes <em>must not</em> have
65 an <tt class="docutils literal">__init___</tt> or <tt class="docutils literal">__new__</tt> method. There should not be any
66 internal state either, except for the data stored in the underlying
67 XML tree. Element instances are created and garbage collected at
68 need, so there is normally no way to predict when and how often a
69 proxy is created for them. Even worse, when the <tt class="docutils literal">__init__</tt> method
70 is called, the object is not even initialized yet to represent the XML
71 tag, so there is not much use in providing an <tt class="docutils literal">__init__</tt> method in
73 <p>Most use cases will not require any class initialisation or proxy
74 state, so you can content yourself with skipping to the next section
75 for now. However, if you really need to set up your element class on
76 instantiation, or need a way to persistently store state in the proxy
77 instances instead of the XML tree, here is a way to do so.</p>
78 <p>There is one important guarantee regarding Element proxies. Once a
79 proxy has been instantiated, it will keep alive as long as there is a
80 Python reference to it, and any access to the XML element in the tree
81 will return this very instance. Therefore, if you need to store local
82 state in a custom Element class (which is generally discouraged), you
83 can do so by keeping the Elements in a tree alive. If the tree
84 doesn't change, you can simply do this:</p>
85 <div class="syntax"><pre><span class="n">proxy_cache</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">root</span><span class="o">.</span><span class="n">iter</span><span class="p">())</span>
88 <div class="syntax"><pre><span class="n">proxy_cache</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">root</span><span class="o">.</span><span class="n">iter</span><span class="p">())</span>
90 <p>or use any other suitable container. Note that you have to keep this
91 cache manually up to date if the tree changes, which can get tricky in
93 <p>For proxy initialisation, ElementBase classes have an <tt class="docutils literal">_init()</tt>
94 method that can be overridden, as oppose to the normal <tt class="docutils literal">__init__()</tt>
95 method. It can be used to modify the XML tree, e.g. to construct
96 special children or verify and update attributes.</p>
97 <p>The semantics of <tt class="docutils literal">_init()</tt> are as follows:</p>
99 <li>It is called once on Element class instantiation time. That is,
100 when a Python representation of the element is created by lxml. At
101 that time, the element object is completely initialized to represent
102 a specific XML element within the tree.</li>
103 <li>The method has complete access to the XML tree. Modifications can be done
104 in exactly the same way as anywhere else in the program.</li>
105 <li>Python representations of elements may be created multiple times during the
106 lifetime of an XML element in the underlying C tree. The <tt class="docutils literal">_init()</tt> code
107 provided by subclasses must take special care by itself that multiple
108 executions either are harmless or that they are prevented by some kind of
109 flag in the XML tree. The latter can be achieved by modifying an attribute
110 value or by removing or adding a specific child node and then verifying this
111 before running through the init process.</li>
112 <li>Any exceptions raised in <tt class="docutils literal">_init()</tt> will be propagated throught the API
113 call that lead to the creation of the Element. So be careful with the code
114 you write here as its exceptions may turn up in various unexpected places.</li>
117 <div class="section" id="setting-up-a-class-lookup-scheme">
118 <h1>Setting up a class lookup scheme</h1>
119 <p>The first thing to do when deploying custom element classes is to register a
120 class lookup scheme on a parser. lxml.etree provides quite a number of
121 different schemes that also support class lookup based on namespaces or
122 attribute values. Most lookups support fallback chaining, which allows the
123 next lookup mechanism to take over when the previous one fails to find a
125 <p>For example, setting the <tt class="docutils literal">honk</tt> Element as a default element class
126 for a parser works as follows:</p>
127 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">parser_lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementDefaultClassLookup</span><span class="p">(</span><span class="n">element</span><span class="o">=</span><span class="n">honk</span><span class="p">)</span>
128 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
129 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">parser_lookup</span><span class="p">)</span>
131 <p>There is one drawback of the parser based scheme: the <tt class="docutils literal">Element()</tt> factory
132 does not know about your specialised parser and creates a new document that
133 deploys the default parser:</p>
134 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">Element</span><span class="p">(</span><span class="s">"root"</span><span class="p">)</span>
135 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">el</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
136 <span class="go">False</span>
138 <p>You should therefore avoid using this factory function in code that
139 uses custom classes. The <tt class="docutils literal">makeelement()</tt> method of parsers provides
140 a simple replacement:</p>
141 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">makeelement</span><span class="p">(</span><span class="s">"root"</span><span class="p">)</span>
142 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">el</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
143 <span class="go">True</span>
145 <p>If you use a parser at the module level, you can easily redirect a module
146 level <tt class="docutils literal">Element()</tt> factory to the parser method by adding code like this:</p>
147 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">module_level_parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
148 <span class="gp">>>> </span><span class="n">Element</span> <span class="o">=</span> <span class="n">module_level_parser</span><span class="o">.</span><span class="n">makeelement</span>
150 <p>While the <tt class="docutils literal">XML()</tt> and <tt class="docutils literal">HTML()</tt> factories also depend on the default
151 parser, you can pass them a different parser as second argument:</p>
152 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">element</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s">"<test/>"</span><span class="p">)</span>
153 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
154 <span class="go">False</span>
156 <span class="gp">>>> </span><span class="n">element</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s">"<test/>"</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
157 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
158 <span class="go">True</span>
160 <p>Whenever you create a document with a parser, it will inherit the lookup
161 scheme and all subsequent element instantiations for this document will use
163 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">element</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">fromstring</span><span class="p">(</span><span class="s">"<test/>"</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
164 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
165 <span class="go">True</span>
166 <span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="s">"subel"</span><span class="p">)</span>
167 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">el</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
168 <span class="go">True</span>
170 <p>For testing code in the Python interpreter and for small projects, you
171 may also consider setting a lookup scheme on the default parser. To
172 avoid interfering with other modules, however, it is usually a better
173 idea to use a dedicated parser for each module (or a parser pool when
174 using threads) and then register the required lookup scheme only for
176 <div class="section" id="default-class-lookup">
177 <h2>Default class lookup</h2>
178 <p>This is the most simple lookup mechanism. It always returns the default
179 element class. Consequently, no further fallbacks are supported, but this
180 scheme is a nice fallback for other custom lookup mechanisms.</p>
182 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementDefaultClassLookup</span><span class="p">()</span>
183 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
184 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
186 <p>Note that the default for new parsers is to use the global fallback, which is
187 also the default lookup (if not configured otherwise).</p>
188 <p>To change the default element implementation, you can pass your new class to
189 the constructor. While it accepts classes for <tt class="docutils literal">element</tt>, <tt class="docutils literal">comment</tt> and
190 <tt class="docutils literal">pi</tt> nodes, most use cases will only override the element class:</p>
191 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">makeelement</span><span class="p">(</span><span class="s">"myelement"</span><span class="p">)</span>
192 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">el</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
193 <span class="go">False</span>
195 <span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementDefaultClassLookup</span><span class="p">(</span><span class="n">element</span><span class="o">=</span><span class="n">honk</span><span class="p">)</span>
196 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
198 <span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">makeelement</span><span class="p">(</span><span class="s">"myelement"</span><span class="p">)</span>
199 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">el</span><span class="p">,</span> <span class="n">honk</span><span class="p">))</span>
200 <span class="go">True</span>
201 <span class="gp">>>> </span><span class="n">el</span><span class="o">.</span><span class="n">honking</span>
202 <span class="go">False</span>
203 <span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">makeelement</span><span class="p">(</span><span class="s">"myelement"</span><span class="p">,</span> <span class="n">honking</span><span class="o">=</span><span class="s">'true'</span><span class="p">)</span>
204 <span class="gp">>>> </span><span class="n">etree</span><span class="o">.</span><span class="n">tostring</span><span class="p">(</span><span class="n">el</span><span class="p">)</span>
205 <span class="go">b'<myelement honking="true"/>'</span>
206 <span class="gp">>>> </span><span class="n">el</span><span class="o">.</span><span class="n">honking</span>
207 <span class="go">True</span>
210 <div class="section" id="namespace-class-lookup">
211 <h2>Namespace class lookup</h2>
212 <p>This is an advanced lookup mechanism that supports namespace/tag-name specific
213 element classes. You can select it by calling:</p>
214 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementNamespaceClassLookup</span><span class="p">()</span>
215 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
216 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
218 <p>See the separate section on <a class="reference external" href="#implementing-namespaces">implementing namespaces</a> below to learn how to
220 <p>This scheme supports a fallback mechanism that is used in the case where the
221 namespace is not found or no class was registered for the element name.
222 Normally, the default class lookup is used here. To change it, pass the
223 desired fallback lookup scheme to the constructor:</p>
224 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">fallback</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementDefaultClassLookup</span><span class="p">(</span><span class="n">element</span><span class="o">=</span><span class="n">honk</span><span class="p">)</span>
225 <span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementNamespaceClassLookup</span><span class="p">(</span><span class="n">fallback</span><span class="p">)</span>
226 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
229 <div class="section" id="attribute-based-lookup">
230 <h2>Attribute based lookup</h2>
231 <p>This scheme uses a mapping from attribute values to classes. An attribute
232 name is set at initialisation time and is then used to find the corresponding
233 value in a dictionary. It is set up as follows:</p>
234 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">id_class_mapping</span> <span class="o">=</span> <span class="p">{</span><span class="s">'1234'</span> <span class="p">:</span> <span class="n">honk</span><span class="p">}</span> <span class="c"># maps attribute values to classes</span>
236 <span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">AttributeBasedElementClassLookup</span><span class="p">(</span>
237 <span class="gp">... </span> <span class="s">'id'</span><span class="p">,</span> <span class="n">id_class_mapping</span><span class="p">)</span>
238 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
239 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
241 <p>And here is how to use it:</p>
242 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">xml</span> <span class="o">=</span> <span class="s">'<a id="123"><b id="1234"/><b id="1234" honking="true"/></a>'</span>
243 <span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">fromstring</span><span class="p">(</span><span class="n">xml</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
245 <span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">honking</span> <span class="c"># id does not match !</span>
246 <span class="gt">Traceback (most recent call last):</span>
247 <span class="gr">AttributeError</span>: <span class="n">'lxml.etree._Element' object has no attribute 'honking'</span>
249 <span class="gp">>>> </span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">honking</span>
250 <span class="go">False</span>
251 <span class="gp">>>> </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">honking</span>
252 <span class="go">True</span>
254 <p>This lookup scheme uses its fallback if the attribute is not found or
255 its value is not in the mapping. Normally, the default class lookup
256 is used here. If you want to use the namespace lookup, for example,
257 you can use this code:</p>
258 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">fallback</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementNamespaceClassLookup</span><span class="p">()</span>
259 <span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">AttributeBasedElementClassLookup</span><span class="p">(</span>
260 <span class="gp">... </span> <span class="s">'id'</span><span class="p">,</span> <span class="n">id_class_mapping</span><span class="p">,</span> <span class="n">fallback</span><span class="p">)</span>
261 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
262 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
265 <div class="section" id="custom-element-class-lookup">
266 <h2>Custom element class lookup</h2>
267 <p>This is the most customisable way of finding element classes on a per-element
268 basis. It allows you to implement a custom lookup scheme in a subclass:</p>
269 <div class="syntax"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">MyLookup</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">CustomElementClassLookup</span><span class="p">):</span>
270 <span class="gp">... </span> <span class="k">def</span> <span class="nf">lookup</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node_type</span><span class="p">,</span> <span class="n">document</span><span class="p">,</span> <span class="n">namespace</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
271 <span class="gp">... </span> <span class="k">return</span> <span class="n">honk</span> <span class="c"># be a bit more selective here ...</span>
273 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
274 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">MyLookup</span><span class="p">())</span>
276 <p>The <tt class="docutils literal">.lookup()</tt> method must return either None (which triggers the
277 fallback mechanism) or a subclass of <tt class="docutils literal">lxml.etree.ElementBase</tt>. It
278 can take any decision it wants based on the node type (one of
279 "element", "comment", "PI", "entity"), the XML document of the
280 element, or its namespace or tag name.</p>
282 <div class="section" id="tree-based-element-class-lookup-in-python">
283 <h2>Tree based element class lookup in Python</h2>
284 <p>Taking more elaborate decisions than allowed by the custom scheme is
285 difficult to achieve in pure Python, as it results in a
286 chicken-and-egg problem. It would require access to the tree - before
287 the elements in the tree have been instantiated as Python Element
289 <p>Luckily, there is a way to do this. The <tt class="docutils literal">PythonElementClassLookup</tt>
290 works similar to the custom lookup scheme:</p>
291 <div class="syntax"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">MyLookup</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">PythonElementClassLookup</span><span class="p">):</span>
292 <span class="gp">... </span> <span class="k">def</span> <span class="nf">lookup</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">document</span><span class="p">,</span> <span class="n">element</span><span class="p">):</span>
293 <span class="gp">... </span> <span class="k">return</span> <span class="n">MyElementClass</span> <span class="c"># defined elsewhere</span>
295 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
296 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">MyLookup</span><span class="p">())</span>
298 <p>As before, the first argument to the <tt class="docutils literal">lookup()</tt> method is the opaque
299 document instance that contains the Element. The second arguments is a
300 lightweight Element proxy implementation that is only valid during the lookup.
301 Do not try to keep a reference to it. Once the lookup is finished, the proxy
302 will become invalid. You will get an <tt class="docutils literal">AssertionError</tt> if you access any of
303 the properties or methods outside the scope of the lookup call where they were
305 <p>During the lookup, the element object behaves mostly like a normal Element
306 instance. It provides the properties <tt class="docutils literal">tag</tt>, <tt class="docutils literal">text</tt>, <tt class="docutils literal">tail</tt> etc. and
307 supports indexing, slicing and the <tt class="docutils literal">getchildren()</tt>, <tt class="docutils literal">getparent()</tt>
308 etc. methods. It does <em>not</em> support iteration, nor does it support any kind
309 of modification. All of its properties are read-only and it cannot be removed
310 or inserted into other trees. You can use it as a starting point to freely
311 traverse the tree and collect any kind of information that its elements
312 provide. Once you have taken the decision which class to use for this
313 element, you can simply return it and have lxml take care of cleaning up the
314 instantiated proxy classes.</p>
315 <p>Sidenote: this lookup scheme originally lived in a separate module called
316 <tt class="docutils literal">lxml.pyclasslookup</tt>.</p>
319 <div class="section" id="generating-xml-with-custom-classes">
320 <h1>Generating XML with custom classes</h1>
321 <p>Up to lxml 2.1, you could not instantiate proxy classes yourself.
322 Only lxml.etree could do that when creating an object representation
323 of an existing XML element. Since lxml 2.2, however, instantiating
324 this class will simply create a new Element:</p>
325 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">honk</span><span class="p">(</span><span class="n">honking</span> <span class="o">=</span> <span class="s">'true'</span><span class="p">)</span>
326 <span class="gp">>>> </span><span class="n">el</span><span class="o">.</span><span class="n">tag</span>
327 <span class="go">'honk'</span>
328 <span class="gp">>>> </span><span class="n">el</span><span class="o">.</span><span class="n">honking</span>
329 <span class="go">True</span>
331 <p>Note, however, that the proxy you create here will be garbage
332 collected just like any other proxy. You can therefore not count on
333 lxml.etree using the same class that you instantiated when you access
334 this Element a second time after letting its reference go. You should
335 therefore always use a corresponding class lookup scheme that returns
336 your Element proxy classes for the elements that they create. The
337 <tt class="docutils literal">ElementNamespaceClassLookup</tt> is generally a good match.</p>
338 <p>You can use custom Element classes to quickly create XML fragments:</p>
339 <div class="syntax"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">hale</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">ElementBase</span><span class="p">):</span> <span class="k">pass</span>
340 <span class="gp">>>> </span><span class="k">class</span> <span class="nc">bopp</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">ElementBase</span><span class="p">):</span> <span class="k">pass</span>
342 <span class="gp">>>> </span><span class="n">el</span> <span class="o">=</span> <span class="n">hale</span><span class="p">(</span> <span class="s">"some "</span><span class="p">,</span> <span class="n">honk</span><span class="p">(</span><span class="n">honking</span> <span class="o">=</span> <span class="s">'true'</span><span class="p">),</span> <span class="n">bopp</span><span class="p">,</span> <span class="s">" text"</span> <span class="p">)</span>
344 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">tostring</span><span class="p">(</span><span class="n">el</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'unicode'</span><span class="p">))</span>
345 <span class="go"><hale>some <honk honking="true"/><bopp/> text</hale></span>
348 <div class="section" id="id1">
349 <h1>Implementing namespaces</h1>
350 <p>lxml allows you to implement namespaces, in a rather literal sense. After
351 setting up the namespace class lookup mechanism as described above, you can
352 build a new element namespace (or retrieve an existing one) by calling the
353 <tt class="docutils literal">get_namespace(uri)</tt> method of the lookup:</p>
354 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">lookup</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">ElementNamespaceClassLookup</span><span class="p">()</span>
355 <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">()</span>
356 <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">set_element_class_lookup</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
358 <span class="gp">>>> </span><span class="n">namespace</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_namespace</span><span class="p">(</span><span class="s">'http://hui.de/honk'</span><span class="p">)</span>
360 <p>and then register the new element type with that namespace, say, under the tag
361 name <tt class="docutils literal">honk</tt>:</p>
362 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">namespace</span><span class="p">[</span><span class="s">'honk'</span><span class="p">]</span> <span class="o">=</span> <span class="n">honk</span>
364 <p>If you have many Element classes declared in one module, and they are
365 all named like the elements they create, you can simply use
366 <tt class="docutils literal"><span class="pre">namespace.update(vars())</span></tt> at the end of your module to declare them
367 automatically. The implementation is smart enough to ignore
368 everything that is not an Element class.</p>
369 <p>After this, you create and use your XML elements through the normal API of
371 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">xml</span> <span class="o">=</span> <span class="s">'<honk xmlns="http://hui.de/honk" honking="true"/>'</span>
372 <span class="gp">>>> </span><span class="n">honk_element</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="n">xml</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
373 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="o">.</span><span class="n">honking</span><span class="p">)</span>
374 <span class="go">True</span>
376 <p>The same works when creating elements by hand:</p>
377 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">honk_element</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">makeelement</span><span class="p">(</span><span class="s">'{http://hui.de/honk}honk'</span><span class="p">,</span>
378 <span class="gp">... </span> <span class="n">honking</span><span class="o">=</span><span class="s">'true'</span><span class="p">)</span>
379 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="o">.</span><span class="n">honking</span><span class="p">)</span>
380 <span class="go">True</span>
382 <p>Essentially, what this allows you to do, is to give Elements a custom API
383 based on their namespace and tag name.</p>
384 <p>A somewhat related topic are <a class="reference external" href="extensions.html">extension functions</a> which use a similar
385 mechanism for registering extension functions in XPath and XSLT.</p>
386 <p>In the setup example above, we associated the <tt class="docutils literal">honk</tt> Element class
387 only with the 'honk' element. If an XML tree contains different
388 elements in the same namespace, they do not pick up the same
390 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">xml</span> <span class="o">=</span> <span class="s">'<honk xmlns="http://hui.de/honk" honking="true"><bla/></honk>'</span>
391 <span class="gp">>>> </span><span class="n">honk_element</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="n">xml</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
392 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="o">.</span><span class="n">honking</span><span class="p">)</span>
393 <span class="go">True</span>
394 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">honking</span><span class="p">)</span>
395 <span class="gt">Traceback (most recent call last):</span>
396 <span class="c">...</span>
397 <span class="gr">AttributeError</span>: <span class="n">'lxml.etree._Element' object has no attribute 'honking'</span>
399 <p>You can therefore provide one implementation per element name in each
400 namespace and have lxml select the right one on the fly. If you want one
401 element implementation per namespace (ignoring the element name) or prefer
402 having a common class for most elements except a few, you can specify a
403 default implementation for an entire namespace by registering that class with
404 the empty element name (None).</p>
405 <p>You may consider following an object oriented approach here. If you build a
406 class hierarchy of element classes, you can also implement a base class for a
407 namespace that is used if no specific element class is provided. Again, you
408 can just pass None as an element name:</p>
409 <div class="syntax"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">HonkNSElement</span><span class="p">(</span><span class="n">etree</span><span class="o">.</span><span class="n">ElementBase</span><span class="p">):</span>
410 <span class="gp">... </span> <span class="k">def</span> <span class="nf">honk</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
411 <span class="gp">... </span> <span class="k">return</span> <span class="s">"HONK"</span>
412 <span class="gp">>>> </span><span class="n">namespace</span><span class="p">[</span><span class="bp">None</span><span class="p">]</span> <span class="o">=</span> <span class="n">HonkNSElement</span> <span class="c"># default Element for namespace</span>
414 <span class="gp">>>> </span><span class="k">class</span> <span class="nc">HonkElement</span><span class="p">(</span><span class="n">HonkNSElement</span><span class="p">):</span>
415 <span class="gp">... </span> <span class="nd">@property</span>
416 <span class="gp">... </span> <span class="k">def</span> <span class="nf">honking</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
417 <span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'honking'</span><span class="p">)</span> <span class="o">==</span> <span class="s">'true'</span>
418 <span class="gp">>>> </span><span class="n">namespace</span><span class="p">[</span><span class="s">'honk'</span><span class="p">]</span> <span class="o">=</span> <span class="n">HonkElement</span> <span class="c"># Element for specific tag</span>
420 <p>Now you can rely on lxml to always return objects of type HonkNSElement or its
421 subclasses for elements of this namespace:</p>
422 <div class="syntax"><pre><span class="gp">>>> </span><span class="n">xml</span> <span class="o">=</span> <span class="s">'<honk xmlns="http://hui.de/honk" honking="true"><bla/></honk>'</span>
423 <span class="gp">>>> </span><span class="n">honk_element</span> <span class="o">=</span> <span class="n">etree</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="n">xml</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
425 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">honk_element</span><span class="p">))</span>
426 <span class="go"><class 'HonkElement'></span>
427 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">honk_element</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
428 <span class="go"><class 'HonkNSElement'></span>
430 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="o">.</span><span class="n">honking</span><span class="p">)</span>
431 <span class="go">True</span>
432 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="o">.</span><span class="n">honk</span><span class="p">())</span>
433 <span class="go">HONK</span>
435 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">honk</span><span class="p">())</span>
436 <span class="go">HONK</span>
437 <span class="gp">>>> </span><span class="k">print</span><span class="p">(</span><span class="n">honk_element</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">honking</span><span class="p">)</span>
438 <span class="gt">Traceback (most recent call last):</span>
439 <span class="c">...</span>
440 <span class="gr">AttributeError</span>: <span class="n">'HonkNSElement' object has no attribute 'honking'</span>
445 <hr class="footer" />
446 Generated on: 2012-07-31.