Sophie

Sophie

distrib > CentOS > 5 > i386 > by-pkgid > 90dba77ca23efa667b541b5c0dd77497 > files > 378

python-lxml-2.0.11-2.el5.i386.rpm

<!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>Extension functions for XPath and XSLT</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="document" id="extension-functions-for-xpath-and-xslt">
<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 current" 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 foreign" 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">Extension functions for XPath and XSLT</h1>
<p>This document describes how to use Python extension functions in XPath and
XSLT.  They allow you to do things like this:</p>
<pre class="literal-block">
&lt;xsl:value-of select="f:myPythonFunction(.//sometag)" /&gt;
</pre>
<p>Here is how such a function looks like.  As the first argument, it always
receives a context object (see below).  The other arguments are provided by
the respective call in the XPath expression, one in the following examples.
Any number of arguments is allowed:</p>
<pre class="literal-block">
&gt;&gt;&gt; def hello(dummy, a):
...    return "Hello %s" % a
&gt;&gt;&gt; def ola(dummy, a):
...    return "Ola %s" % a
&gt;&gt;&gt; def loadsofargs(dummy, *args):
...    return "Got %d arguments." % len(args)
</pre>
<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="#the-functionnamespace" id="id1" name="id1">The FunctionNamespace</a></li>
<li><a class="reference" href="#global-prefix-assignment" id="id2" name="id2">Global prefix assignment</a></li>
<li><a class="reference" href="#the-xpath-context" id="id3" name="id3">The XPath context</a></li>
<li><a class="reference" href="#evaluators-and-xslt" id="id4" name="id4">Evaluators and XSLT</a></li>
<li><a class="reference" href="#evaluator-local-extensions" id="id5" name="id5">Evaluator-local extensions</a></li>
<li><a class="reference" href="#what-to-return-from-a-function" id="id6" name="id6">What to return from a function</a></li>
</ul>
</div>
<div class="section">
<h1><a id="the-functionnamespace" name="the-functionnamespace">The FunctionNamespace</a></h1>
<p>In order to use a function in XPath/XSLT, it needs to have a (namespaced) name
by which it can be called during evaluation.  This is done using the
FunctionNamespace class.  For simplicity, we choose the empty namespace
(None):</p>
<pre class="literal-block">
&gt;&gt;&gt; from lxml import etree
&gt;&gt;&gt; ns = etree.FunctionNamespace(None)
&gt;&gt;&gt; ns['hello'] = hello
&gt;&gt;&gt; ns['countargs'] = loadsofargs
</pre>
<p>This registers the function <cite>hello</cite> with the name <cite>hello</cite> in the default
namespace (None), and the function <cite>loadsofargs</cite> with the name <cite>countargs</cite>.
Now we're going to create a document that we can run XPath expressions
against:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML('&lt;a&gt;&lt;b&gt;Haegar&lt;/b&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc = etree.ElementTree(root)
</pre>
<p>Done. Now we can have XPath expressions call our new function:</p>
<pre class="literal-block">
&gt;&gt;&gt; print root.xpath("hello('world')")
Hello world
&gt;&gt;&gt; print root.xpath('hello(local-name(*))')
Hello b
&gt;&gt;&gt; print root.xpath('hello(string(b))')
Hello Haegar
&gt;&gt;&gt; print root.xpath('countargs(., b, ./*)')
Got 3 arguments.
</pre>
<p>Note how we call both a Python function (<cite>hello</cite>) and an XPath built-in
function (<cite>string</cite>) in exactly the same way.  Normally, however, you would
want to separate the two in different namespaces.  The FunctionNamespace class
allows you to do this:</p>
<pre class="literal-block">
&gt;&gt;&gt; ns = etree.FunctionNamespace('http://mydomain.org/myfunctions')
&gt;&gt;&gt; ns['hello'] = hello
&gt;&gt;&gt; prefixmap = {'f' : 'http://mydomain.org/myfunctions'}
&gt;&gt;&gt; print root.xpath('f:hello(local-name(*))', namespaces=prefixmap)
Hello b
</pre>
</div>
<div class="section">
<h1><a id="global-prefix-assignment" name="global-prefix-assignment">Global prefix assignment</a></h1>
<p>In the last example, you had to specify a prefix for the function namespace.
If you always use the same prefix for a function namespace, you can also
register it with the namespace:</p>
<pre class="literal-block">
&gt;&gt;&gt; ns = etree.FunctionNamespace('http://mydomain.org/myother/functions')
&gt;&gt;&gt; ns.prefix = 'es'
&gt;&gt;&gt; ns['hello'] = ola
&gt;&gt;&gt; print root.xpath('es:hello(local-name(*))')
Ola b
</pre>
<p>This is a global assignment, so take care not to assign the same prefix to
more than one namespace.  The resulting behaviour in that case is completely
undefined.  It is always a good idea to consistently use the same meaningful
prefix for each namespace throughout your application.</p>
<p>The prefix assignment only works with functions and FunctionNamespace objects,
not with the general Namespace object that registers element classes.  The
reasoning is that elements in lxml do not care about prefixes anyway, so it
would rather complicate things than be of any help.</p>
</div>
<div class="section">
<h1><a id="the-xpath-context" name="the-xpath-context">The XPath context</a></h1>
<p>Functions get a context object as first parameter.  In lxml 1.x, this value
was None, but since lxml 2.0 it provides two properties: <tt class="docutils literal"><span class="pre">eval_context</span></tt> and
<tt class="docutils literal"><span class="pre">context_node</span></tt>.  The context node is the Element where the current function
is called:</p>
<pre class="literal-block">
&gt;&gt;&gt; def print_tag(context, nodes):
...     print context.context_node.tag, [ n.tag for n in nodes ]

&gt;&gt;&gt; ns = etree.FunctionNamespace('http://mydomain.org/printtag')
&gt;&gt;&gt; ns.prefix = "pt"
&gt;&gt;&gt; ns["print_tag"] = print_tag

&gt;&gt;&gt; ignore = root.xpath("//*[pt:print_tag(.//*)]")
a ['b']
b []
</pre>
<p>The <tt class="docutils literal"><span class="pre">eval_context</span></tt> is a dictionary that is local to the evaluation.  It
allows functions to keep state:</p>
<pre class="literal-block">
&gt;&gt;&gt; def print_context(context):
...     context.eval_context[context.context_node.tag] = "done"
...     entries = context.eval_context.items()
...     entries.sort()
...     print entries
&gt;&gt;&gt; ns["print_context"] = print_context

&gt;&gt;&gt; ignore = root.xpath("//*[pt:print_context()]")
[('a', 'done')]
[('a', 'done'), ('b', 'done')]
</pre>
</div>
<div class="section">
<h1><a id="evaluators-and-xslt" name="evaluators-and-xslt">Evaluators and XSLT</a></h1>
<p>Extension functions work for all ways of evaluating XPath expressions and for
XSL transformations:</p>
<pre class="literal-block">
&gt;&gt;&gt; e = etree.XPathEvaluator(doc)
&gt;&gt;&gt; print e.evaluate('es:hello(local-name(/a))')
Ola a

&gt;&gt;&gt; namespaces = {'f' : 'http://mydomain.org/myfunctions'}
&gt;&gt;&gt; e = etree.XPathEvaluator(doc, namespaces=namespaces)
&gt;&gt;&gt; print e.evaluate('f:hello(local-name(/a))')
Hello a

&gt;&gt;&gt; xslt = etree.XSLT(etree.XML('''
...   &lt;stylesheet version="1.0"
...          xmlns="http://www.w3.org/1999/XSL/Transform"
...          xmlns:es="http://mydomain.org/myother/functions"&gt;
...     &lt;output method="text" encoding="ASCII"/&gt;
...     &lt;template match="/"&gt;
...       &lt;value-of select="es:hello(string(//b))"/&gt;
...     &lt;/template&gt;
...   &lt;/stylesheet&gt;
... '''))
&gt;&gt;&gt; print xslt(doc)
Ola Haegar
</pre>
<p>It is also possible to register namespaces with a single evaluator after its
creation.  While the following example involves no functions, the idea should
still be clear:</p>
<pre class="literal-block">
&gt;&gt;&gt; from StringIO import StringIO
&gt;&gt;&gt; f = StringIO('&lt;a xmlns="http://mydomain.org/myfunctions" /&gt;')
&gt;&gt;&gt; ns_doc = etree.parse(f)
&gt;&gt;&gt; e = etree.XPathEvaluator(ns_doc)
&gt;&gt;&gt; e.evaluate('/a')
[]
</pre>
<p>This returns nothing, as we did not ask for the right namespace.  When we
register the namespace with the evaluator, however, we can access it via a
prefix:</p>
<pre class="literal-block">
&gt;&gt;&gt; e.registerNamespace('foo', 'http://mydomain.org/myfunctions')
&gt;&gt;&gt; e.evaluate('/foo:a')[0].tag
'{http://mydomain.org/myfunctions}a'
</pre>
<p>Note that this prefix mapping is only known to this evaluator, as opposed to
the global mapping of the FunctionNamespace objects:</p>
<pre class="literal-block">
&gt;&gt;&gt; e2 = etree.XPathEvaluator(ns_doc)
&gt;&gt;&gt; e2.evaluate('/foo:a')
Traceback (most recent call last):
...
XPathEvalError: Undefined namespace prefix
</pre>
</div>
<div class="section">
<h1><a id="evaluator-local-extensions" name="evaluator-local-extensions">Evaluator-local extensions</a></h1>
<p>Apart from the global registration of extension functions, there is also a way
of making extensions known to a single Evaluator or XSLT.  All evaluators and
the XSLT object accept a keyword argument <tt class="docutils literal"><span class="pre">extensions</span></tt> in their constructor.
The value is a dictionary mapping (namespace, name) tuples to functions:</p>
<pre class="literal-block">
&gt;&gt;&gt; extensions = {('local-ns', 'local-hello') : hello}
&gt;&gt;&gt; namespaces = {'l' : 'local-ns'}

&gt;&gt;&gt; e = etree.XPathEvaluator(doc, namespaces=namespaces, extensions=extensions)
&gt;&gt;&gt; print e.evaluate('l:local-hello(string(b))')
Hello Haegar
</pre>
<p>For larger numbers of extension functions, you can define classes or modules
and use the <tt class="docutils literal"><span class="pre">Extension</span></tt> helper:</p>
<pre class="literal-block">
&gt;&gt;&gt; class MyExt:
...     def function1(self, _, arg):
...         return '1'+arg
...     def function2(self, _, arg):
...         return '2'+arg
...     def function3(self, _, arg):
...         return '3'+arg

&gt;&gt;&gt; ext_module = MyExt()
&gt;&gt;&gt; functions = ('function1', 'function2')
&gt;&gt;&gt; extensions = etree.Extension( ext_module, functions, ns='local-ns' )

&gt;&gt;&gt; e = etree.XPathEvaluator(doc, namespaces=namespaces, extensions=extensions)
&gt;&gt;&gt; print e.evaluate('l:function1(string(b))')
1Haegar
</pre>
<p>The optional second argument to <tt class="docutils literal"><span class="pre">Extension</span></tt> can either be be a
sequence of names to select from the module, a dictionary that
explicitly maps function names to their XPath alter-ego or <tt class="docutils literal"><span class="pre">None</span></tt>
(explicitly passed) to take all available functions under their
original name (if their name does not start with '_').</p>
<p>The additional <tt class="docutils literal"><span class="pre">ns</span></tt> keyword argument takes a namespace URI or
<tt class="docutils literal"><span class="pre">None</span></tt> (also if left out) for the default namespace.  The following
examples will therefore all do the same thing:</p>
<pre class="literal-block">
&gt;&gt;&gt; functions = ('function1', 'function2', 'function3')
&gt;&gt;&gt; extensions = etree.Extension( ext_module, functions )
&gt;&gt;&gt; e = etree.XPathEvaluator(doc, extensions=extensions)
&gt;&gt;&gt; print e.evaluate('function1(function2(function3(string(b))))')
123Haegar

&gt;&gt;&gt; extensions = etree.Extension( ext_module, functions, ns=None )
&gt;&gt;&gt; e = etree.XPathEvaluator(doc, extensions=extensions)
&gt;&gt;&gt; print e.evaluate('function1(function2(function3(string(b))))')
123Haegar

&gt;&gt;&gt; extensions = etree.Extension(ext_module)
&gt;&gt;&gt; e = etree.XPathEvaluator(doc, extensions=extensions)
&gt;&gt;&gt; print e.evaluate('function1(function2(function3(string(b))))')
123Haegar

&gt;&gt;&gt; functions = {
...     'function1' : 'function1',
...     'function2' : 'function2',
...     'function3' : 'function3'
...     }
&gt;&gt;&gt; extensions = etree.Extension(ext_module, functions)
&gt;&gt;&gt; e = etree.XPathEvaluator(doc, extensions=extensions)
&gt;&gt;&gt; print e.evaluate('function1(function2(function3(string(b))))')
123Haegar
</pre>
<p>For convenience, you can also pass a sequence of extensions:</p>
<pre class="literal-block">
&gt;&gt;&gt; extensions1 = etree.Extension(ext_module)
&gt;&gt;&gt; extensions2 = etree.Extension(ext_module, ns='local-ns')
&gt;&gt;&gt; e = etree.XPathEvaluator(doc, extensions=[extensions1, extensions2],
...                          namespaces=namespaces)
&gt;&gt;&gt; print e.evaluate('function1(l:function2(function3(string(b))))')
123Haegar
</pre>
</div>
<div class="section">
<h1><a id="what-to-return-from-a-function" name="what-to-return-from-a-function">What to return from a function</a></h1>
<p>Extension functions can return any data type for which there is an XPath
equivalent (see the documentation on <cite>XPath return values</cite>).  This includes
numbers, boolean values, elements and lists of elements.  Note that integers
will also be returned as floats:</p>
<pre class="literal-block">
&gt;&gt;&gt; def returnsFloat(_):
...    return 1.7
&gt;&gt;&gt; def returnsInteger(_):
...    return 1
&gt;&gt;&gt; def returnsBool(_):
...    return True
&gt;&gt;&gt; def returnFirstNode(_, nodes):
...    return nodes[0]

&gt;&gt;&gt; ns = etree.FunctionNamespace(None)
&gt;&gt;&gt; ns['float'] = returnsFloat
&gt;&gt;&gt; ns['int']   = returnsInteger
&gt;&gt;&gt; ns['bool']  = returnsBool
&gt;&gt;&gt; ns['first'] = returnFirstNode

&gt;&gt;&gt; e = etree.XPathEvaluator(doc)
&gt;&gt;&gt; e.evaluate("float()")
1.7
&gt;&gt;&gt; e.evaluate("int()")
1.0
&gt;&gt;&gt; int( e.evaluate("int()") )
1
&gt;&gt;&gt; e.evaluate("bool()")
True
&gt;&gt;&gt; e.evaluate("count(first(//b))")
1.0
</pre>
<p>As the last example shows, you can pass the results of functions back into
the XPath expression.  Elements and sequences of elements are treated as
XPath node-sets:</p>
<pre class="literal-block">
&gt;&gt;&gt; def returnsNodeSet(_):
...     results1 = etree.Element('results1')
...     etree.SubElement(results1, 'result').text = "Alpha"
...     etree.SubElement(results1, 'result').text = "Beta"
...
...     results2 = etree.Element('results2')
...     etree.SubElement(results2, 'result').text = "Gamma"
...     etree.SubElement(results2, 'result').text = "Delta"
...
...     results3 = etree.SubElement(results2, 'subresult')
...     return [results1, results2, results3]

&gt;&gt;&gt; ns['new-node-set'] = returnsNodeSet

&gt;&gt;&gt; e = etree.XPathEvaluator(doc)

&gt;&gt;&gt; r = e.evaluate("new-node-set()/result")
&gt;&gt;&gt; print [ t.text for t in r ]
['Alpha', 'Beta', 'Gamma', 'Delta']

&gt;&gt;&gt; r = e.evaluate("new-node-set()")
&gt;&gt;&gt; print [ t.tag for t in r ]
['results1', 'results2', 'subresult']
&gt;&gt;&gt; print [ len(t) for t in r ]
[2, 3, 0]
&gt;&gt;&gt; r[0][0].text
'Alpha'

&gt;&gt;&gt; print etree.tostring(r[0])
&lt;results1&gt;&lt;result&gt;Alpha&lt;/result&gt;&lt;result&gt;Beta&lt;/result&gt;&lt;/results1&gt;

&gt;&gt;&gt; print etree.tostring(r[1])
&lt;results2&gt;&lt;result&gt;Gamma&lt;/result&gt;&lt;result&gt;Delta&lt;/result&gt;&lt;subresult/&gt;&lt;/results2&gt;

&gt;&gt;&gt; print etree.tostring(r[2])
&lt;subresult/&gt;
</pre>
<p>The current implementation deep-copies newly created elements in node-sets.
Only the elements and their children are passed on, no outlying parents or
tail texts will be available in the result.  This also means that in the above
example, the <cite>subresult</cite> elements in <cite>results2</cite> and <cite>results3</cite> are no longer
identical within the node-set, they belong to independent trees:</p>
<pre class="literal-block">
&gt;&gt;&gt; print r[1][-1].tag, r[2].tag
subresult subresult
&gt;&gt;&gt; print r[1][-1] == r[2]
False
&gt;&gt;&gt; print r[1][-1].getparent().tag
results2
&gt;&gt;&gt; print r[2].getparent()
None
</pre>
<p>This is an implementation detail that you should be aware of, but you should
avoid relying on it in your code.  Note that elements taken from the source
document (the most common case) do not suffer from this restriction.  They
will always be passed unchanged.</p>
</div>
</div>
<div class="footer">
<hr class="footer" />
Generated on: 2008-12-12.

</div>
</body>
</html>