| 1 |
==================================== |
| 2 |
Python extensions for XPath and XSLT |
| 3 |
==================================== |
| 4 |
|
| 5 |
This document describes how to use Python extension functions in XPath |
| 6 |
and XSLT like this: |
| 7 |
|
| 8 |
.. sourcecode:: xml |
| 9 |
|
| 10 |
<xsl:value-of select="f:myPythonFunction(.//sometag)" /> |
| 11 |
|
| 12 |
and extension elements in XSLT as in the following example: |
| 13 |
|
| 14 |
.. sourcecode:: xml |
| 15 |
|
| 16 |
<xsl:template match="*"> |
| 17 |
<my:python-extension> |
| 18 |
<some-content /> |
| 19 |
</my:python-extension> |
| 20 |
</xsl:template> |
| 21 |
|
| 22 |
|
| 23 |
.. contents:: |
| 24 |
.. |
| 25 |
1 XPath Extension functions |
| 26 |
1.1 The FunctionNamespace |
| 27 |
1.2 Global prefix assignment |
| 28 |
1.3 The XPath context |
| 29 |
1.4 Evaluators and XSLT |
| 30 |
1.5 Evaluator-local extensions |
| 31 |
1.6 What to return from a function |
| 32 |
2 XSLT extension elements |
| 33 |
2.1 Declaring extension elements |
| 34 |
2.2 Applying XSL templates |
| 35 |
2.3 Working with read-only elements |
| 36 |
|
| 37 |
.. |
| 38 |
>>> try: from StringIO import StringIO |
| 39 |
... except ImportError: |
| 40 |
... from io import BytesIO |
| 41 |
... def StringIO(s): |
| 42 |
... if isinstance(s, str): s = s.encode("UTF-8") |
| 43 |
... return BytesIO(s) |
| 44 |
|
| 45 |
|
| 46 |
XPath Extension functions |
| 47 |
========================= |
| 48 |
|
| 49 |
Here is what an extension function looks like. As the first argument, |
| 50 |
it always receives a context object (see below). The other arguments |
| 51 |
are provided by the respective call in the XPath expression, one in |
| 52 |
the following examples. Any number of arguments is allowed: |
| 53 |
|
| 54 |
.. sourcecode:: pycon |
| 55 |
|
| 56 |
>>> def hello(context, a): |
| 57 |
... return "Hello %s" % a |
| 58 |
>>> def ola(context, a): |
| 59 |
... return "Ola %s" % a |
| 60 |
>>> def loadsofargs(context, *args): |
| 61 |
... return "Got %d arguments." % len(args) |
| 62 |
|
| 63 |
|
| 64 |
The FunctionNamespace |
| 65 |
--------------------- |
| 66 |
|
| 67 |
In order to use a function in XPath or XSLT, it needs to have a |
| 68 |
(namespaced) name by which it can be called during evaluation. This |
| 69 |
is done using the FunctionNamespace class. For simplicity, we choose |
| 70 |
the empty namespace (None): |
| 71 |
|
| 72 |
.. sourcecode:: pycon |
| 73 |
|
| 74 |
>>> from lxml import etree |
| 75 |
>>> ns = etree.FunctionNamespace(None) |
| 76 |
>>> ns['hello'] = hello |
| 77 |
>>> ns['countargs'] = loadsofargs |
| 78 |
|
| 79 |
This registers the function `hello` with the name `hello` in the default |
| 80 |
namespace (None), and the function `loadsofargs` with the name `countargs`. |
| 81 |
|
| 82 |
Since lxml 4.1, it is preferred to use the ``FunctionNamespace`` as a decorator. |
| 83 |
Either pass an explicit function name (``@ns("countargs")``), or just use the |
| 84 |
bare decorator to register the function under its own name: |
| 85 |
|
| 86 |
.. sourcecode:: pycon |
| 87 |
|
| 88 |
>>> @ns |
| 89 |
... def hello(context, a): |
| 90 |
... return "Hello %s" % a |
| 91 |
|
| 92 |
Now we're going to create a document that we can run XPath expressions |
| 93 |
against: |
| 94 |
|
| 95 |
.. sourcecode:: pycon |
| 96 |
|
| 97 |
>>> root = etree.XML('<a><b>Haegar</b></a>') |
| 98 |
>>> doc = etree.ElementTree(root) |
| 99 |
|
| 100 |
Done. Now we can have XPath expressions call our new function: |
| 101 |
|
| 102 |
.. sourcecode:: pycon |
| 103 |
|
| 104 |
>>> print(root.xpath("hello('Dr. Falken')")) |
| 105 |
Hello Dr. Falken |
| 106 |
>>> print(root.xpath('hello(local-name(*))')) |
| 107 |
Hello b |
| 108 |
>>> print(root.xpath('hello(string(b))')) |
| 109 |
Hello Haegar |
| 110 |
>>> print(root.xpath('countargs(., b, ./*)')) |
| 111 |
Got 3 arguments. |
| 112 |
|
| 113 |
Note how we call both a Python function (``hello()``) and an XPath built-in |
| 114 |
function (``string()``) in exactly the same way. Normally, however, you would |
| 115 |
want to separate the two in different namespaces. The FunctionNamespace class |
| 116 |
allows you to do this: |
| 117 |
|
| 118 |
.. sourcecode:: pycon |
| 119 |
|
| 120 |
>>> ns = etree.FunctionNamespace('http://mydomain.org/myfunctions') |
| 121 |
>>> ns['hello'] = hello |
| 122 |
|
| 123 |
>>> prefixmap = {'f' : 'http://mydomain.org/myfunctions'} |
| 124 |
>>> print(root.xpath('f:hello(local-name(*))', namespaces=prefixmap)) |
| 125 |
Hello b |
| 126 |
|
| 127 |
|
| 128 |
Global prefix assignment |
| 129 |
------------------------ |
| 130 |
|
| 131 |
In the last example, you had to specify a prefix for the function namespace. |
| 132 |
If you always use the same prefix for a function namespace, you can also |
| 133 |
register it with the namespace: |
| 134 |
|
| 135 |
.. sourcecode:: pycon |
| 136 |
|
| 137 |
>>> ns = etree.FunctionNamespace('http://mydomain.org/myother/functions') |
| 138 |
>>> ns.prefix = 'es' |
| 139 |
>>> ns['hello'] = ola |
| 140 |
|
| 141 |
>>> print(root.xpath('es:hello(local-name(*))')) |
| 142 |
Ola b |
| 143 |
|
| 144 |
This is a global assignment, so take care not to assign the same prefix to |
| 145 |
more than one namespace. The resulting behaviour in that case is completely |
| 146 |
undefined. It is always a good idea to consistently use the same meaningful |
| 147 |
prefix for each namespace throughout your application. |
| 148 |
|
| 149 |
The prefix assignment only works with functions and FunctionNamespace objects, |
| 150 |
not with the general Namespace object that registers element classes. The |
| 151 |
reasoning is that elements in lxml do not care about prefixes anyway, so it |
| 152 |
would rather complicate things than be of any help. |
| 153 |
|
| 154 |
|
| 155 |
The XPath context |
| 156 |
----------------- |
| 157 |
|
| 158 |
Functions get a context object as first parameter. In lxml 1.x, this value |
| 159 |
was None, but since lxml 2.0 it provides two properties: ``eval_context`` and |
| 160 |
``context_node``. The context node is the Element where the current function |
| 161 |
is called: |
| 162 |
|
| 163 |
.. sourcecode:: pycon |
| 164 |
|
| 165 |
>>> def print_tag(context, nodes): |
| 166 |
... print("%s: %s" % (context.context_node.tag, [ n.tag for n in nodes ])) |
| 167 |
|
| 168 |
>>> ns = etree.FunctionNamespace('http://mydomain.org/printtag') |
| 169 |
>>> ns.prefix = "pt" |
| 170 |
>>> ns["print_tag"] = print_tag |
| 171 |
|
| 172 |
>>> ignore = root.xpath("//*[pt:print_tag(.//*)]") |
| 173 |
a: ['b'] |
| 174 |
b: [] |
| 175 |
|
| 176 |
The ``eval_context`` is a dictionary that is local to the evaluation. It |
| 177 |
allows functions to keep state: |
| 178 |
|
| 179 |
.. sourcecode:: pycon |
| 180 |
|
| 181 |
>>> def print_context(context): |
| 182 |
... context.eval_context[context.context_node.tag] = "done" |
| 183 |
... print(sorted(context.eval_context.items())) |
| 184 |
>>> ns["print_context"] = print_context |
| 185 |
|
| 186 |
>>> ignore = root.xpath("//*[pt:print_context()]") |
| 187 |
[('a', 'done')] |
| 188 |
[('a', 'done'), ('b', 'done')] |
| 189 |
|
| 190 |
|
| 191 |
Evaluators and XSLT |
| 192 |
------------------- |
| 193 |
|
| 194 |
Extension functions work for all ways of evaluating XPath expressions and for |
| 195 |
XSL transformations: |
| 196 |
|
| 197 |
.. sourcecode:: pycon |
| 198 |
|
| 199 |
>>> e = etree.XPathEvaluator(doc) |
| 200 |
>>> print(e('es:hello(local-name(/a))')) |
| 201 |
Ola a |
| 202 |
|
| 203 |
>>> namespaces = {'f' : 'http://mydomain.org/myfunctions'} |
| 204 |
>>> e = etree.XPathEvaluator(doc, namespaces=namespaces) |
| 205 |
>>> print(e('f:hello(local-name(/a))')) |
| 206 |
Hello a |
| 207 |
|
| 208 |
>>> xslt = etree.XSLT(etree.XML(''' |
| 209 |
... <stylesheet version="1.0" |
| 210 |
... xmlns="http://www.w3.org/1999/XSL/Transform" |
| 211 |
... xmlns:es="http://mydomain.org/myother/functions"> |
| 212 |
... <output method="text" encoding="ASCII"/> |
| 213 |
... <template match="/"> |
| 214 |
... <value-of select="es:hello(string(//b))"/> |
| 215 |
... </template> |
| 216 |
... </stylesheet> |
| 217 |
... ''')) |
| 218 |
>>> print(xslt(doc)) |
| 219 |
Ola Haegar |
| 220 |
|
| 221 |
It is also possible to register namespaces with a single evaluator after its |
| 222 |
creation. While the following example involves no functions, the idea should |
| 223 |
still be clear: |
| 224 |
|
| 225 |
.. sourcecode:: pycon |
| 226 |
|
| 227 |
>>> f = StringIO('<a xmlns="http://mydomain.org/myfunctions" />') |
| 228 |
>>> ns_doc = etree.parse(f) |
| 229 |
>>> e = etree.XPathEvaluator(ns_doc) |
| 230 |
>>> e('/a') |
| 231 |
[] |
| 232 |
|
| 233 |
This returns nothing, as we did not ask for the right namespace. When we |
| 234 |
register the namespace with the evaluator, however, we can access it via a |
| 235 |
prefix: |
| 236 |
|
| 237 |
.. sourcecode:: pycon |
| 238 |
|
| 239 |
>>> e.register_namespace('foo', 'http://mydomain.org/myfunctions') |
| 240 |
>>> e('/foo:a')[0].tag |
| 241 |
'{http://mydomain.org/myfunctions}a' |
| 242 |
|
| 243 |
Note that this prefix mapping is only known to this evaluator, as opposed to |
| 244 |
the global mapping of the FunctionNamespace objects: |
| 245 |
|
| 246 |
.. sourcecode:: pycon |
| 247 |
|
| 248 |
>>> e2 = etree.XPathEvaluator(ns_doc) |
| 249 |
>>> e2('/foo:a') |
| 250 |
Traceback (most recent call last): |
| 251 |
... |
| 252 |
lxml.etree.XPathEvalError: Undefined namespace prefix... |
| 253 |
|
| 254 |
|
| 255 |
Evaluator-local extensions |
| 256 |
-------------------------- |
| 257 |
|
| 258 |
Apart from the global registration of extension functions, there is also a way |
| 259 |
of making extensions known to a single Evaluator or XSLT. All evaluators and |
| 260 |
the XSLT object accept a keyword argument ``extensions`` in their constructor. |
| 261 |
The value is a dictionary mapping (namespace, name) tuples to functions: |
| 262 |
|
| 263 |
.. sourcecode:: pycon |
| 264 |
|
| 265 |
>>> extensions = {('local-ns', 'local-hello') : hello} |
| 266 |
>>> namespaces = {'l' : 'local-ns'} |
| 267 |
|
| 268 |
>>> e = etree.XPathEvaluator(doc, namespaces=namespaces, extensions=extensions) |
| 269 |
>>> print(e('l:local-hello(string(b))')) |
| 270 |
Hello Haegar |
| 271 |
|
| 272 |
For larger numbers of extension functions, you can define classes or modules |
| 273 |
and use the ``Extension`` helper: |
| 274 |
|
| 275 |
.. sourcecode:: pycon |
| 276 |
|
| 277 |
>>> class MyExt: |
| 278 |
... def function1(self, _, arg): |
| 279 |
... return '1'+arg |
| 280 |
... def function2(self, _, arg): |
| 281 |
... return '2'+arg |
| 282 |
... def function3(self, _, arg): |
| 283 |
... return '3'+arg |
| 284 |
|
| 285 |
>>> ext_module = MyExt() |
| 286 |
>>> functions = ('function1', 'function2') |
| 287 |
>>> extensions = etree.Extension( ext_module, functions, ns='local-ns' ) |
| 288 |
|
| 289 |
>>> e = etree.XPathEvaluator(doc, namespaces=namespaces, extensions=extensions) |
| 290 |
>>> print(e('l:function1(string(b))')) |
| 291 |
1Haegar |
| 292 |
|
| 293 |
The optional second argument to ``Extension`` can either be a |
| 294 |
sequence of names to select from the module, a dictionary that |
| 295 |
explicitly maps function names to their XPath alter-ego or ``None`` |
| 296 |
(explicitly passed) to take all available functions under their |
| 297 |
original name (if their name does not start with '_'). |
| 298 |
|
| 299 |
The additional ``ns`` keyword argument takes a namespace URI or |
| 300 |
``None`` (also if left out) for the default namespace. The following |
| 301 |
examples will therefore all do the same thing: |
| 302 |
|
| 303 |
.. sourcecode:: pycon |
| 304 |
|
| 305 |
>>> functions = ('function1', 'function2', 'function3') |
| 306 |
>>> extensions = etree.Extension( ext_module, functions ) |
| 307 |
>>> e = etree.XPathEvaluator(doc, extensions=extensions) |
| 308 |
>>> print(e('function1(function2(function3(string(b))))')) |
| 309 |
123Haegar |
| 310 |
|
| 311 |
>>> extensions = etree.Extension( ext_module, functions, ns=None ) |
| 312 |
>>> e = etree.XPathEvaluator(doc, extensions=extensions) |
| 313 |
>>> print(e('function1(function2(function3(string(b))))')) |
| 314 |
123Haegar |
| 315 |
|
| 316 |
>>> extensions = etree.Extension(ext_module) |
| 317 |
>>> e = etree.XPathEvaluator(doc, extensions=extensions) |
| 318 |
>>> print(e('function1(function2(function3(string(b))))')) |
| 319 |
123Haegar |
| 320 |
|
| 321 |
>>> functions = { |
| 322 |
... 'function1' : 'function1', |
| 323 |
... 'function2' : 'function2', |
| 324 |
... 'function3' : 'function3' |
| 325 |
... } |
| 326 |
>>> extensions = etree.Extension(ext_module, functions) |
| 327 |
>>> e = etree.XPathEvaluator(doc, extensions=extensions) |
| 328 |
>>> print(e('function1(function2(function3(string(b))))')) |
| 329 |
123Haegar |
| 330 |
|
| 331 |
For convenience, you can also pass a sequence of extensions: |
| 332 |
|
| 333 |
.. sourcecode:: pycon |
| 334 |
|
| 335 |
>>> extensions1 = etree.Extension(ext_module) |
| 336 |
>>> extensions2 = etree.Extension(ext_module, ns='local-ns') |
| 337 |
>>> e = etree.XPathEvaluator(doc, extensions=[extensions1, extensions2], |
| 338 |
... namespaces=namespaces) |
| 339 |
>>> print(e('function1(l:function2(function3(string(b))))')) |
| 340 |
123Haegar |
| 341 |
|
| 342 |
|
| 343 |
What to return from a function |
| 344 |
------------------------------ |
| 345 |
|
| 346 |
.. _`XPath return values`: xpathxslt.html#xpath-return-values |
| 347 |
|
| 348 |
Extension functions can return any data type for which there is an XPath |
| 349 |
equivalent (see the documentation on `XPath return values`). This includes |
| 350 |
numbers, boolean values, elements and lists of elements. Note that integers |
| 351 |
will also be returned as floats: |
| 352 |
|
| 353 |
.. sourcecode:: pycon |
| 354 |
|
| 355 |
>>> def returnsFloat(_): |
| 356 |
... return 1.7 |
| 357 |
>>> def returnsInteger(_): |
| 358 |
... return 1 |
| 359 |
>>> def returnsBool(_): |
| 360 |
... return True |
| 361 |
>>> def returnFirstNode(_, nodes): |
| 362 |
... return nodes[0] |
| 363 |
|
| 364 |
>>> ns = etree.FunctionNamespace(None) |
| 365 |
>>> ns['float'] = returnsFloat |
| 366 |
>>> ns['int'] = returnsInteger |
| 367 |
>>> ns['bool'] = returnsBool |
| 368 |
>>> ns['first'] = returnFirstNode |
| 369 |
|
| 370 |
>>> e = etree.XPathEvaluator(doc) |
| 371 |
>>> e("float()") |
| 372 |
1.7 |
| 373 |
>>> e("int()") |
| 374 |
1.0 |
| 375 |
>>> int( e("int()") ) |
| 376 |
1 |
| 377 |
>>> e("bool()") |
| 378 |
True |
| 379 |
>>> e("count(first(//b))") |
| 380 |
1.0 |
| 381 |
|
| 382 |
As the last example shows, you can pass the results of functions back into |
| 383 |
the XPath expression. Elements and sequences of elements are treated as |
| 384 |
XPath node-sets: |
| 385 |
|
| 386 |
.. sourcecode:: pycon |
| 387 |
|
| 388 |
>>> def returnsNodeSet(_): |
| 389 |
... results1 = etree.Element('results1') |
| 390 |
... etree.SubElement(results1, 'result').text = "Alpha" |
| 391 |
... etree.SubElement(results1, 'result').text = "Beta" |
| 392 |
... |
| 393 |
... results2 = etree.Element('results2') |
| 394 |
... etree.SubElement(results2, 'result').text = "Gamma" |
| 395 |
... etree.SubElement(results2, 'result').text = "Delta" |
| 396 |
... |
| 397 |
... results3 = etree.SubElement(results2, 'subresult') |
| 398 |
... return [results1, results2, results3] |
| 399 |
|
| 400 |
>>> ns['new-node-set'] = returnsNodeSet |
| 401 |
|
| 402 |
>>> e = etree.XPathEvaluator(doc) |
| 403 |
|
| 404 |
>>> r = e("new-node-set()/result") |
| 405 |
>>> print([ t.text for t in r ]) |
| 406 |
['Alpha', 'Beta', 'Gamma', 'Delta'] |
| 407 |
|
| 408 |
>>> r = e("new-node-set()") |
| 409 |
>>> print([ t.tag for t in r ]) |
| 410 |
['results1', 'results2', 'subresult'] |
| 411 |
>>> print([ len(t) for t in r ]) |
| 412 |
[2, 3, 0] |
| 413 |
>>> r[0][0].text |
| 414 |
'Alpha' |
| 415 |
|
| 416 |
>>> etree.tostring(r[0]) |
| 417 |
b'<results1><result>Alpha</result><result>Beta</result></results1>' |
| 418 |
|
| 419 |
>>> etree.tostring(r[1]) |
| 420 |
b'<results2><result>Gamma</result><result>Delta</result><subresult/></results2>' |
| 421 |
|
| 422 |
>>> etree.tostring(r[2]) |
| 423 |
b'<subresult/>' |
| 424 |
|
| 425 |
The current implementation deep-copies newly created elements in node-sets. |
| 426 |
Only the elements and their children are passed on, no outlying parents or |
| 427 |
tail texts will be available in the result. This also means that in the above |
| 428 |
example, the `subresult` elements in `results2` and `results3` are no longer |
| 429 |
identical within the node-set, they belong to independent trees: |
| 430 |
|
| 431 |
.. sourcecode:: pycon |
| 432 |
|
| 433 |
>>> print("%s - %s" % (r[1][-1].tag, r[2].tag)) |
| 434 |
subresult - subresult |
| 435 |
>>> print(r[1][-1] == r[2]) |
| 436 |
False |
| 437 |
>>> print(r[1][-1].getparent().tag) |
| 438 |
results2 |
| 439 |
>>> print(r[2].getparent()) |
| 440 |
None |
| 441 |
|
| 442 |
This is an implementation detail that you should be aware of, but you should |
| 443 |
avoid relying on it in your code. Note that elements taken from the source |
| 444 |
document (the most common case) do not suffer from this restriction. They |
| 445 |
will always be passed unchanged. |
| 446 |
|
| 447 |
|
| 448 |
XSLT extension elements |
| 449 |
======================= |
| 450 |
|
| 451 |
Just like the XPath extension functions described above, lxml supports |
| 452 |
custom extension *elements* in XSLT. This means, you can write XSLT |
| 453 |
code like this: |
| 454 |
|
| 455 |
.. sourcecode:: xml |
| 456 |
|
| 457 |
<xsl:template match="*"> |
| 458 |
<my:python-extension> |
| 459 |
<some-content /> |
| 460 |
</my:python-extension> |
| 461 |
</xsl:template> |
| 462 |
|
| 463 |
And then you can implement the element in Python like this: |
| 464 |
|
| 465 |
.. sourcecode:: pycon |
| 466 |
|
| 467 |
>>> class MyExtElement(etree.XSLTExtension): |
| 468 |
... def execute(self, context, self_node, input_node, output_parent): |
| 469 |
... print("Hello from XSLT!") |
| 470 |
... output_parent.text = "I did it!" |
| 471 |
... # just copy own content input to output |
| 472 |
... output_parent.extend( list(self_node) ) |
| 473 |
|
| 474 |
The arguments passed to the ``.execute()`` method are |
| 475 |
|
| 476 |
context |
| 477 |
The opaque evaluation context. You need this when calling back |
| 478 |
into the XSLT processor. |
| 479 |
|
| 480 |
self_node |
| 481 |
A read-only Element object that represents the extension element |
| 482 |
in the stylesheet. |
| 483 |
|
| 484 |
input_node |
| 485 |
The current context Element in the input document (also read-only). |
| 486 |
|
| 487 |
output_parent |
| 488 |
The current insertion point in the output document. You can |
| 489 |
append elements or set the text value (not the tail). Apart from |
| 490 |
that, the Element is read-only. |
| 491 |
|
| 492 |
|
| 493 |
Declaring extension elements |
| 494 |
---------------------------- |
| 495 |
|
| 496 |
In XSLT, extension elements can be used like any other XSLT element, |
| 497 |
except that they must be declared as extensions using the standard |
| 498 |
XSLT ``extension-element-prefixes`` option: |
| 499 |
|
| 500 |
.. sourcecode:: pycon |
| 501 |
|
| 502 |
>>> xslt_ext_tree = etree.XML(''' |
| 503 |
... <xsl:stylesheet version="1.0" |
| 504 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform" |
| 505 |
... xmlns:my="testns" |
| 506 |
... extension-element-prefixes="my"> |
| 507 |
... <xsl:template match="/"> |
| 508 |
... <foo><my:ext><child>XYZ</child></my:ext></foo> |
| 509 |
... </xsl:template> |
| 510 |
... <xsl:template match="child"> |
| 511 |
... <CHILD>--xyz--</CHILD> |
| 512 |
... </xsl:template> |
| 513 |
... </xsl:stylesheet>''') |
| 514 |
|
| 515 |
To register the extension, add its namespace and name to the extension |
| 516 |
mapping of the XSLT object: |
| 517 |
|
| 518 |
.. sourcecode:: pycon |
| 519 |
|
| 520 |
>>> my_extension = MyExtElement() |
| 521 |
>>> extensions = { ('testns', 'ext') : my_extension } |
| 522 |
>>> transform = etree.XSLT(xslt_ext_tree, extensions = extensions) |
| 523 |
|
| 524 |
Note how we pass an instance here, not the class of the extension. |
| 525 |
Now we can run the transformation and see how our extension is |
| 526 |
called: |
| 527 |
|
| 528 |
.. sourcecode:: pycon |
| 529 |
|
| 530 |
>>> root = etree.XML('<dummy/>') |
| 531 |
>>> result = transform(root) |
| 532 |
Hello from XSLT! |
| 533 |
>>> str(result) |
| 534 |
'<?xml version="1.0"?>\n<foo>I did it!<child>XYZ</child></foo>\n' |
| 535 |
|
| 536 |
|
| 537 |
Applying XSL templates |
| 538 |
---------------------- |
| 539 |
|
| 540 |
XSLT extensions are a very powerful feature that allows you to |
| 541 |
interact directly with the XSLT processor. You have full read-only |
| 542 |
access to the input document and the stylesheet, and you can even call |
| 543 |
back into the XSLT processor to process templates. Here is an example |
| 544 |
that passes an Element into the ``.apply_templates()`` method of the |
| 545 |
``XSLTExtension`` instance: |
| 546 |
|
| 547 |
.. sourcecode:: pycon |
| 548 |
|
| 549 |
>>> class MyExtElement(etree.XSLTExtension): |
| 550 |
... def execute(self, context, self_node, input_node, output_parent): |
| 551 |
... child = self_node[0] |
| 552 |
... results = self.apply_templates(context, child) |
| 553 |
... output_parent.append(results[0]) |
| 554 |
|
| 555 |
>>> my_extension = MyExtElement() |
| 556 |
>>> extensions = { ('testns', 'ext') : my_extension } |
| 557 |
>>> transform = etree.XSLT(xslt_ext_tree, extensions = extensions) |
| 558 |
|
| 559 |
>>> root = etree.XML('<dummy/>') |
| 560 |
>>> result = transform(root) |
| 561 |
>>> str(result) |
| 562 |
'<?xml version="1.0"?>\n<foo><CHILD>--xyz--</CHILD></foo>\n' |
| 563 |
|
| 564 |
Here, we applied the templates to a child of the extension element |
| 565 |
itself, i.e. to an element inside the stylesheet instead of an element |
| 566 |
of the input document. |
| 567 |
|
| 568 |
The return value of ``.apply_templates()`` is always a list. It may |
| 569 |
contain a mix of elements and strings, collected from the XSLT processing |
| 570 |
result. If you want to append these values to the output parent, be aware |
| 571 |
that you cannot use the ``.append()`` method to add strings. In many |
| 572 |
cases, you would only be interested in elements anyway, so you can discard |
| 573 |
strings (e.g. formatting whitespace) and append the rest. |
| 574 |
|
| 575 |
If you want to include string results in the output, you can either build |
| 576 |
an appropriate tree yourself and append that, or you can manually add the |
| 577 |
string values to the current output tree, e.g. by concatenating them with |
| 578 |
the ``.tail`` of the last element that was appended. |
| 579 |
|
| 580 |
Note that you can also let lxml build the result tree for you by passing |
| 581 |
the ``output_parent`` into the ``.apply_templates()`` method. In this |
| 582 |
case, the result will be None and all content found by applying templates |
| 583 |
will be appended to the output parent. |
| 584 |
|
| 585 |
If you do not care about string results at all, e.g. because you already |
| 586 |
know that they will only contain whitespace, you can pass the option |
| 587 |
``elements_only=True`` to the ``.apply_templates()`` method, or pass |
| 588 |
``remove_blank_text=True`` to remove only those strings that consist |
| 589 |
entirely of whitespace. |
| 590 |
|
| 591 |
|
| 592 |
Working with read-only elements |
| 593 |
------------------------------- |
| 594 |
|
| 595 |
There is one important thing to keep in mind: all Elements that the |
| 596 |
``execute()`` method gets to deal with are read-only Elements, so you |
| 597 |
cannot modify them. They also will not easily work in the API. For |
| 598 |
example, you cannot pass them to the ``tostring()`` function or wrap |
| 599 |
them in an ``ElementTree``. |
| 600 |
|
| 601 |
What you can do, however, is to deepcopy them to make them normal |
| 602 |
Elements, and then modify them using the normal etree API. So this |
| 603 |
will work: |
| 604 |
|
| 605 |
.. sourcecode:: pycon |
| 606 |
|
| 607 |
>>> from copy import deepcopy |
| 608 |
>>> class MyExtElement(etree.XSLTExtension): |
| 609 |
... def execute(self, context, self_node, input_node, output_parent): |
| 610 |
... child = deepcopy(self_node[0]) |
| 611 |
... child.text = "NEW TEXT" |
| 612 |
... output_parent.append(child) |
| 613 |
|
| 614 |
>>> my_extension = MyExtElement() |
| 615 |
>>> extensions = { ('testns', 'ext') : my_extension } |
| 616 |
>>> transform = etree.XSLT(xslt_ext_tree, extensions = extensions) |
| 617 |
|
| 618 |
>>> root = etree.XML('<dummy/>') |
| 619 |
>>> result = transform(root) |
| 620 |
>>> str(result) |
| 621 |
'<?xml version="1.0"?>\n<foo><child>NEW TEXT</child></foo>\n' |