| 1 |
======================== |
| 2 |
XPath and XSLT with lxml |
| 3 |
======================== |
| 4 |
|
| 5 |
lxml supports XPath 1.0, XSLT 1.0 and the EXSLT extensions through |
| 6 |
libxml2 and libxslt in a standards compliant way. |
| 7 |
|
| 8 |
.. contents:: |
| 9 |
.. |
| 10 |
1 XPath |
| 11 |
1.1 The ``xpath()`` method |
| 12 |
1.2 Namespaces and prefixes |
| 13 |
1.3 XPath return values |
| 14 |
1.4 Generating XPath expressions |
| 15 |
1.5 The ``XPath`` class |
| 16 |
1.6 Regular expressions in XPath |
| 17 |
1.7 The ``XPathEvaluator`` classes |
| 18 |
1.8 ``ETXPath`` |
| 19 |
1.9 Error handling |
| 20 |
2 XSLT |
| 21 |
2.1 XSLT result objects |
| 22 |
2.2 Stylesheet parameters |
| 23 |
2.3 The ``xslt()`` tree method |
| 24 |
2.4 Dealing with stylesheet complexity |
| 25 |
2.5 Profiling |
| 26 |
|
| 27 |
The usual setup procedure: |
| 28 |
|
| 29 |
.. sourcecode:: pycon |
| 30 |
|
| 31 |
>>> from lxml import etree |
| 32 |
|
| 33 |
.. |
| 34 |
>>> try: from StringIO import StringIO |
| 35 |
... except ImportError: |
| 36 |
... from io import BytesIO |
| 37 |
... def StringIO(s): |
| 38 |
... if isinstance(s, str): s = s.encode("UTF-8") |
| 39 |
... return BytesIO(s) |
| 40 |
|
| 41 |
>>> import sys |
| 42 |
>>> if sys.version_info[0] == 2: |
| 43 |
... from __builtin__ import unicode as str |
| 44 |
|
| 45 |
|
| 46 |
XPath |
| 47 |
===== |
| 48 |
|
| 49 |
lxml.etree supports the simple path syntax of the |
| 50 |
`find, findall and findtext |
| 51 |
<https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.find>`_ |
| 52 |
methods on ElementTree and Element, as known from the original |
| 53 |
ElementTree / ``xml.etree`` library (ElementPath_). As an lxml specific extension, |
| 54 |
these classes also provide an ``xpath()`` method that supports expressions in the |
| 55 |
complete XPath syntax, as well as `custom extension functions`_. |
| 56 |
|
| 57 |
.. _ElementPath: https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support |
| 58 |
.. _`custom extension functions`: extensions.html#xpath-extension-functions |
| 59 |
.. _`XSLT extension elements`: extensions.html#xslt-extension-elements |
| 60 |
|
| 61 |
There are also specialized XPath evaluator classes that are more efficient for |
| 62 |
frequent evaluation: ``XPath`` and ``XPathEvaluator``. See the `performance |
| 63 |
comparison`_ to learn when to use which. Their semantics when used on |
| 64 |
Elements and ElementTrees are the same as for the ``xpath()`` method described |
| 65 |
here. |
| 66 |
|
| 67 |
.. note:: |
| 68 |
|
| 69 |
The ``.find*()`` methods are usually *faster* than the full-blown XPath |
| 70 |
support. They also support incremental tree processing through the |
| 71 |
``.iterfind()`` method, whereas XPath always collects all results before |
| 72 |
returning them. They are therefore recommended over XPath for both speed |
| 73 |
and memory reasons, whenever there is no need for highly selective XPath |
| 74 |
queries. |
| 75 |
|
| 76 |
.. _`performance comparison`: performance.html#xpath |
| 77 |
|
| 78 |
|
| 79 |
The ``xpath()`` method |
| 80 |
---------------------- |
| 81 |
|
| 82 |
For ElementTree, the xpath method performs a global XPath query against the |
| 83 |
document (if absolute) or against the root node (if relative): |
| 84 |
|
| 85 |
.. sourcecode:: pycon |
| 86 |
|
| 87 |
>>> f = StringIO('<foo><bar></bar></foo>') |
| 88 |
>>> tree = etree.parse(f) |
| 89 |
|
| 90 |
>>> r = tree.xpath('/foo/bar') |
| 91 |
>>> len(r) |
| 92 |
1 |
| 93 |
>>> r[0].tag |
| 94 |
'bar' |
| 95 |
|
| 96 |
>>> r = tree.xpath('bar') |
| 97 |
>>> r[0].tag |
| 98 |
'bar' |
| 99 |
|
| 100 |
When ``xpath()`` is used on an Element, the XPath expression is evaluated |
| 101 |
against the element (if relative) or against the root tree (if absolute): |
| 102 |
|
| 103 |
.. sourcecode:: pycon |
| 104 |
|
| 105 |
>>> root = tree.getroot() |
| 106 |
>>> r = root.xpath('bar') |
| 107 |
>>> r[0].tag |
| 108 |
'bar' |
| 109 |
|
| 110 |
>>> bar = root[0] |
| 111 |
>>> r = bar.xpath('/foo/bar') |
| 112 |
>>> r[0].tag |
| 113 |
'bar' |
| 114 |
|
| 115 |
>>> tree = bar.getroottree() |
| 116 |
>>> r = tree.xpath('/foo/bar') |
| 117 |
>>> r[0].tag |
| 118 |
'bar' |
| 119 |
|
| 120 |
The ``xpath()`` method has support for XPath variables: |
| 121 |
|
| 122 |
.. sourcecode:: pycon |
| 123 |
|
| 124 |
>>> expr = "//*[local-name() = $name]" |
| 125 |
|
| 126 |
>>> print(root.xpath(expr, name = "foo")[0].tag) |
| 127 |
foo |
| 128 |
|
| 129 |
>>> print(root.xpath(expr, name = "bar")[0].tag) |
| 130 |
bar |
| 131 |
|
| 132 |
>>> print(root.xpath("$text", text = "Hello World!")) |
| 133 |
Hello World! |
| 134 |
|
| 135 |
|
| 136 |
Namespaces and prefixes |
| 137 |
----------------------- |
| 138 |
|
| 139 |
If your XPath expression uses namespace prefixes, you must define them |
| 140 |
in a prefix mapping. To this end, pass a dictionary to the |
| 141 |
``namespaces`` keyword argument that maps the namespace prefixes used |
| 142 |
in the XPath expression to namespace URIs: |
| 143 |
|
| 144 |
.. sourcecode:: pycon |
| 145 |
|
| 146 |
>>> f = StringIO('''\ |
| 147 |
... <a:foo xmlns:a="http://codespeak.net/ns/test1" |
| 148 |
... xmlns:b="http://codespeak.net/ns/test2"> |
| 149 |
... <b:bar>Text</b:bar> |
| 150 |
... </a:foo> |
| 151 |
... ''') |
| 152 |
>>> doc = etree.parse(f) |
| 153 |
|
| 154 |
>>> r = doc.xpath('/x:foo/b:bar', |
| 155 |
... namespaces={'x': 'http://codespeak.net/ns/test1', |
| 156 |
... 'b': 'http://codespeak.net/ns/test2'}) |
| 157 |
>>> len(r) |
| 158 |
1 |
| 159 |
>>> r[0].tag |
| 160 |
'{http://codespeak.net/ns/test2}bar' |
| 161 |
>>> r[0].text |
| 162 |
'Text' |
| 163 |
|
| 164 |
The prefixes you choose here are not linked to the prefixes used |
| 165 |
inside the XML document. The document may define whatever prefixes it |
| 166 |
likes, including the empty prefix, without breaking the above code. |
| 167 |
|
| 168 |
Note that XPath does not have a notion of a default namespace. The |
| 169 |
empty prefix is therefore undefined for XPath and cannot be used in |
| 170 |
namespace prefix mappings. |
| 171 |
|
| 172 |
There is also an optional ``extensions`` argument which is used to |
| 173 |
define `custom extension functions`_ in Python that are local to this |
| 174 |
evaluation. The namespace prefixes that they use in the XPath |
| 175 |
expression must also be defined in the namespace prefix mapping. |
| 176 |
|
| 177 |
|
| 178 |
XPath return values |
| 179 |
------------------- |
| 180 |
|
| 181 |
The return value types of XPath evaluations vary, depending on the |
| 182 |
XPath expression used: |
| 183 |
|
| 184 |
* True or False, when the XPath expression has a boolean result |
| 185 |
|
| 186 |
* a float, when the XPath expression has a numeric result (integer or float) |
| 187 |
|
| 188 |
* a 'smart' string (as described below), when the XPath expression has |
| 189 |
a string result. |
| 190 |
|
| 191 |
* a list of items, when the XPath expression has a list as result. |
| 192 |
The items may include Elements (also comments and processing |
| 193 |
instructions), strings and tuples. Text nodes and attributes in the |
| 194 |
result are returned as 'smart' string values. Namespace |
| 195 |
declarations are returned as tuples of strings: ``(prefix, URI)``. |
| 196 |
|
| 197 |
XPath string results are 'smart' in that they provide a |
| 198 |
``getparent()`` method that knows their origin: |
| 199 |
|
| 200 |
* for attribute values, ``result.getparent()`` returns the Element |
| 201 |
that carries them. An example is ``//foo/@attribute``, where the |
| 202 |
parent would be a ``foo`` Element. |
| 203 |
|
| 204 |
* for the ``text()`` function (as in ``//text()``), it returns the |
| 205 |
Element that contains the text or tail that was returned. |
| 206 |
|
| 207 |
You can distinguish between different text origins with the boolean |
| 208 |
properties ``is_text``, ``is_tail`` and ``is_attribute``. |
| 209 |
|
| 210 |
Note that ``getparent()`` may not always return an Element. For |
| 211 |
example, the XPath functions ``string()`` and ``concat()`` will |
| 212 |
construct strings that do not have an origin. For them, |
| 213 |
``getparent()`` will return None. |
| 214 |
|
| 215 |
There are certain cases where the smart string behaviour is |
| 216 |
undesirable. For example, it means that the tree will be kept alive |
| 217 |
by the string, which may have a considerable memory impact in the case |
| 218 |
that the string value is the only thing in the tree that is actually |
| 219 |
of interest. For these cases, you can deactivate the parental |
| 220 |
relationship using the keyword argument ``smart_strings``. |
| 221 |
|
| 222 |
.. sourcecode:: pycon |
| 223 |
|
| 224 |
>>> root = etree.XML("<root><a>TEXT</a></root>") |
| 225 |
|
| 226 |
>>> find_text = etree.XPath("//text()") |
| 227 |
>>> text = find_text(root)[0] |
| 228 |
>>> print(text) |
| 229 |
TEXT |
| 230 |
>>> print(text.getparent().text) |
| 231 |
TEXT |
| 232 |
|
| 233 |
>>> find_text = etree.XPath("//text()", smart_strings=False) |
| 234 |
>>> text = find_text(root)[0] |
| 235 |
>>> print(text) |
| 236 |
TEXT |
| 237 |
>>> hasattr(text, 'getparent') |
| 238 |
False |
| 239 |
|
| 240 |
|
| 241 |
Generating XPath expressions |
| 242 |
---------------------------- |
| 243 |
|
| 244 |
ElementTree objects have a method ``getpath(element)``, which returns a |
| 245 |
structural, absolute XPath expression to find that element: |
| 246 |
|
| 247 |
.. sourcecode:: pycon |
| 248 |
|
| 249 |
>>> a = etree.Element("a") |
| 250 |
>>> b = etree.SubElement(a, "b") |
| 251 |
>>> c = etree.SubElement(a, "c") |
| 252 |
>>> d1 = etree.SubElement(c, "d") |
| 253 |
>>> d2 = etree.SubElement(c, "d") |
| 254 |
|
| 255 |
>>> tree = etree.ElementTree(c) |
| 256 |
>>> print(tree.getpath(d2)) |
| 257 |
/c/d[2] |
| 258 |
>>> tree.xpath(tree.getpath(d2)) == [d2] |
| 259 |
True |
| 260 |
|
| 261 |
|
| 262 |
The ``XPath`` class |
| 263 |
------------------- |
| 264 |
|
| 265 |
The ``XPath`` class compiles an XPath expression into a callable function: |
| 266 |
|
| 267 |
.. sourcecode:: pycon |
| 268 |
|
| 269 |
>>> root = etree.XML("<root><a><b/></a><b/></root>") |
| 270 |
|
| 271 |
>>> find = etree.XPath("//b") |
| 272 |
>>> print(find(root)[0].tag) |
| 273 |
b |
| 274 |
|
| 275 |
The compilation takes as much time as in the ``xpath()`` method, but it is |
| 276 |
done only once per class instantiation. This makes it especially efficient |
| 277 |
for repeated evaluation of the same XPath expression. |
| 278 |
|
| 279 |
Just like the ``xpath()`` method, the ``XPath`` class supports XPath |
| 280 |
variables: |
| 281 |
|
| 282 |
.. sourcecode:: pycon |
| 283 |
|
| 284 |
>>> count_elements = etree.XPath("count(//*[local-name() = $name])") |
| 285 |
|
| 286 |
>>> print(count_elements(root, name = "a")) |
| 287 |
1.0 |
| 288 |
>>> print(count_elements(root, name = "b")) |
| 289 |
2.0 |
| 290 |
|
| 291 |
This supports very efficient evaluation of modified versions of an XPath |
| 292 |
expression, as compilation is still only required once. |
| 293 |
|
| 294 |
Prefix-to-namespace mappings can be passed as second parameter: |
| 295 |
|
| 296 |
.. sourcecode:: pycon |
| 297 |
|
| 298 |
>>> root = etree.XML("<root xmlns='NS'><a><b/></a><b/></root>") |
| 299 |
|
| 300 |
>>> find = etree.XPath("//n:b", namespaces={'n':'NS'}) |
| 301 |
>>> print(find(root)[0].tag) |
| 302 |
{NS}b |
| 303 |
|
| 304 |
|
| 305 |
Regular expressions in XPath |
| 306 |
---------------------------- |
| 307 |
|
| 308 |
By default, ``XPath`` supports regular expressions in the EXSLT_ namespace: |
| 309 |
|
| 310 |
.. sourcecode:: pycon |
| 311 |
|
| 312 |
>>> regexpNS = "http://exslt.org/regular-expressions" |
| 313 |
>>> find = etree.XPath("//*[re:test(., '^abc$', 'i')]", |
| 314 |
... namespaces={'re':regexpNS}) |
| 315 |
|
| 316 |
>>> root = etree.XML("<root><a>aB</a><b>aBc</b></root>") |
| 317 |
>>> print(find(root)[0].text) |
| 318 |
aBc |
| 319 |
|
| 320 |
.. _EXSLT: https://exslt.github.io/ |
| 321 |
|
| 322 |
You can disable this with the boolean keyword argument ``regexp`` which |
| 323 |
defaults to True. |
| 324 |
|
| 325 |
|
| 326 |
The ``XPathEvaluator`` classes |
| 327 |
------------------------------ |
| 328 |
|
| 329 |
lxml.etree provides two other efficient XPath evaluators that work on |
| 330 |
ElementTrees or Elements respectively: ``XPathDocumentEvaluator`` and |
| 331 |
``XPathElementEvaluator``. They are automatically selected if you use the |
| 332 |
XPathEvaluator helper for instantiation: |
| 333 |
|
| 334 |
.. sourcecode:: pycon |
| 335 |
|
| 336 |
>>> root = etree.XML("<root><a><b/></a><b/></root>") |
| 337 |
>>> xpatheval = etree.XPathEvaluator(root) |
| 338 |
|
| 339 |
>>> print(isinstance(xpatheval, etree.XPathElementEvaluator)) |
| 340 |
True |
| 341 |
|
| 342 |
>>> print(xpatheval("//b")[0].tag) |
| 343 |
b |
| 344 |
|
| 345 |
This class provides efficient support for evaluating different XPath |
| 346 |
expressions on the same Element or ElementTree. |
| 347 |
|
| 348 |
|
| 349 |
``ETXPath`` |
| 350 |
----------- |
| 351 |
|
| 352 |
ElementTree supports a language named ElementPath_ in its ``find*()`` methods. |
| 353 |
One of the main differences between XPath and ElementPath is that the XPath |
| 354 |
language requires an indirection through prefixes for namespace support, |
| 355 |
whereas ElementTree uses the Clark notation (``{ns}name``) to avoid prefixes |
| 356 |
completely. The other major difference regards the capabilities of both path |
| 357 |
languages. Where XPath supports various sophisticated ways of restricting the |
| 358 |
result set through functions and boolean expressions, ElementPath only |
| 359 |
supports pure path traversal without nesting or further conditions. So, while |
| 360 |
the ElementPath syntax is self-contained and therefore easier to write and |
| 361 |
handle, XPath is much more powerful and expressive. |
| 362 |
|
| 363 |
lxml.etree bridges this gap through the class ``ETXPath``, which accepts XPath |
| 364 |
expressions with namespaces in Clark notation. It is identical to the |
| 365 |
``XPath`` class, except for the namespace notation. Normally, you would |
| 366 |
write: |
| 367 |
|
| 368 |
.. sourcecode:: pycon |
| 369 |
|
| 370 |
>>> root = etree.XML("<root xmlns='ns'><a><b/></a><b/></root>") |
| 371 |
|
| 372 |
>>> find = etree.XPath("//p:b", namespaces={'p' : 'ns'}) |
| 373 |
>>> print(find(root)[0].tag) |
| 374 |
{ns}b |
| 375 |
|
| 376 |
``ETXPath`` allows you to change this to: |
| 377 |
|
| 378 |
.. sourcecode:: pycon |
| 379 |
|
| 380 |
>>> find = etree.ETXPath("//{ns}b") |
| 381 |
>>> print(find(root)[0].tag) |
| 382 |
{ns}b |
| 383 |
|
| 384 |
|
| 385 |
Error handling |
| 386 |
-------------- |
| 387 |
|
| 388 |
lxml.etree raises exceptions when errors occur while parsing or evaluating an |
| 389 |
XPath expression: |
| 390 |
|
| 391 |
.. sourcecode:: pycon |
| 392 |
|
| 393 |
>>> find = etree.XPath("\\") |
| 394 |
Traceback (most recent call last): |
| 395 |
... |
| 396 |
lxml.etree.XPathSyntaxError: Invalid expression |
| 397 |
|
| 398 |
lxml will also try to give you a hint what went wrong, so if you pass a more |
| 399 |
complex expression, you may get a somewhat more specific error: |
| 400 |
|
| 401 |
.. sourcecode:: pycon |
| 402 |
|
| 403 |
>>> find = etree.XPath("//*[1.1.1]") |
| 404 |
Traceback (most recent call last): |
| 405 |
... |
| 406 |
lxml.etree.XPathSyntaxError: Invalid predicate |
| 407 |
|
| 408 |
During evaluation, lxml will emit an XPathEvalError on errors: |
| 409 |
|
| 410 |
.. sourcecode:: pycon |
| 411 |
|
| 412 |
>>> find = etree.XPath("//ns:a") |
| 413 |
>>> find(root) |
| 414 |
Traceback (most recent call last): |
| 415 |
... |
| 416 |
lxml.etree.XPathEvalError: Undefined namespace prefix... |
| 417 |
|
| 418 |
This works for the ``XPath`` class, however, the other evaluators (including |
| 419 |
the ``xpath()`` method) are one-shot operations that do parsing and evaluation |
| 420 |
in one step. They therefore raise evaluation exceptions in all cases: |
| 421 |
|
| 422 |
.. sourcecode:: pycon |
| 423 |
|
| 424 |
>>> root = etree.Element("test") |
| 425 |
>>> find = root.xpath("//*[1.1.1]") |
| 426 |
Traceback (most recent call last): |
| 427 |
... |
| 428 |
lxml.etree.XPathEvalError: Invalid predicate |
| 429 |
|
| 430 |
>>> find = root.xpath("//ns:a") |
| 431 |
Traceback (most recent call last): |
| 432 |
... |
| 433 |
lxml.etree.XPathEvalError: Undefined namespace prefix... |
| 434 |
|
| 435 |
>>> find = root.xpath("\\") |
| 436 |
Traceback (most recent call last): |
| 437 |
... |
| 438 |
lxml.etree.XPathEvalError: Invalid expression |
| 439 |
|
| 440 |
Note that lxml versions before 1.3 always raised an ``XPathSyntaxError`` for |
| 441 |
all errors, including evaluation errors. The best way to support older |
| 442 |
versions is to except on the superclass ``XPathError``. |
| 443 |
|
| 444 |
|
| 445 |
XSLT |
| 446 |
==== |
| 447 |
|
| 448 |
lxml.etree introduces a new class, lxml.etree.XSLT. The class can be |
| 449 |
given an ElementTree or Element object to construct an XSLT |
| 450 |
transformer: |
| 451 |
|
| 452 |
.. sourcecode:: pycon |
| 453 |
|
| 454 |
>>> xslt_root = etree.XML('''\ |
| 455 |
... <xsl:stylesheet version="1.0" |
| 456 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
| 457 |
... <xsl:template match="/"> |
| 458 |
... <foo><xsl:value-of select="/a/b/text()" /></foo> |
| 459 |
... </xsl:template> |
| 460 |
... </xsl:stylesheet>''') |
| 461 |
>>> transform = etree.XSLT(xslt_root) |
| 462 |
|
| 463 |
You can then run the transformation on an ElementTree document by simply |
| 464 |
calling it, and this results in another ElementTree object: |
| 465 |
|
| 466 |
.. sourcecode:: pycon |
| 467 |
|
| 468 |
>>> f = StringIO('<a><b>Text</b></a>') |
| 469 |
>>> doc = etree.parse(f) |
| 470 |
>>> result_tree = transform(doc) |
| 471 |
|
| 472 |
By default, XSLT supports all extension functions from libxslt and |
| 473 |
libexslt as well as Python regular expressions through the `EXSLT |
| 474 |
regexp functions`_. Also see the documentation on `custom extension |
| 475 |
functions`_, `XSLT extension elements`_ and `document resolvers`_. |
| 476 |
There is a separate section on `controlling access`_ to external |
| 477 |
documents and resources. |
| 478 |
|
| 479 |
.. _`EXSLT regexp functions`: http://exslt.github.io/regexp/ |
| 480 |
.. _`document resolvers`: resolvers.html |
| 481 |
.. _`controlling access`: resolvers.html#i-o-access-control-in-xslt |
| 482 |
|
| 483 |
.. note:: |
| 484 |
|
| 485 |
Due to a bug in libxslt the usage of ``<xsl:strip-space elements="*"/>`` |
| 486 |
in an XSLT stylesheet can lead to crashes or memory failures. It is therefore |
| 487 |
advised not to use ``xsl:strip-space`` in stylesheets used with lxml. |
| 488 |
|
| 489 |
For details see: https://gitlab.gnome.org/GNOME/libxslt/-/issues/14 |
| 490 |
|
| 491 |
XSLT result objects |
| 492 |
------------------- |
| 493 |
|
| 494 |
The result of an XSL transformation can be accessed like a normal ElementTree |
| 495 |
document: |
| 496 |
|
| 497 |
.. sourcecode:: pycon |
| 498 |
|
| 499 |
>>> root = etree.XML('<a><b>Text</b></a>') |
| 500 |
>>> result = transform(root) |
| 501 |
|
| 502 |
>>> result.getroot().text |
| 503 |
'Text' |
| 504 |
|
| 505 |
but, as opposed to normal ElementTree objects, can also be turned into an (XML |
| 506 |
or text) string by applying the ``bytes()`` function (``str()`` in Python 2): |
| 507 |
|
| 508 |
.. sourcecode:: pycon |
| 509 |
|
| 510 |
>>> bytes(result) |
| 511 |
b'<?xml version="1.0"?>\n<foo>Text</foo>\n' |
| 512 |
|
| 513 |
The result is always a plain string, encoded as requested by the ``xsl:output`` |
| 514 |
element in the stylesheet. If you want a Python Unicode/Text string instead, |
| 515 |
you should set this encoding to ``UTF-8`` (unless the `ASCII` default |
| 516 |
is sufficient). This allows you to call the builtin ``str()`` function on |
| 517 |
the result (``unicode()`` in Python 2): |
| 518 |
|
| 519 |
.. sourcecode:: pycon |
| 520 |
|
| 521 |
>>> str(result) |
| 522 |
'<?xml version="1.0"?>\n<foo>Text</foo>\n' |
| 523 |
|
| 524 |
You can use other encodings at the cost of multiple recoding. Encodings that |
| 525 |
are not supported by Python will result in an error: |
| 526 |
|
| 527 |
.. sourcecode:: pycon |
| 528 |
|
| 529 |
>>> xslt_tree = etree.XML('''\ |
| 530 |
... <xsl:stylesheet version="1.0" |
| 531 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
| 532 |
... <xsl:output encoding="EBCDIC"/> |
| 533 |
... <xsl:template match="/"> |
| 534 |
... <foo><xsl:value-of select="/a/b/text()" /></foo> |
| 535 |
... </xsl:template> |
| 536 |
... </xsl:stylesheet>''') |
| 537 |
>>> transform = etree.XSLT(xslt_tree) |
| 538 |
|
| 539 |
>>> result = transform(doc) |
| 540 |
>>> str(result) |
| 541 |
Traceback (most recent call last): |
| 542 |
... |
| 543 |
LookupError: unknown encoding: EBCDIC |
| 544 |
|
| 545 |
While it is possible to use the ``.write()`` method (known from ``ElementTree`` |
| 546 |
objects) to serialise the XSLT result into a file, it is better to use the |
| 547 |
``.write_output()`` method. The latter knows about the ``<xsl:output>`` tag |
| 548 |
and writes the expected data into the output file. |
| 549 |
|
| 550 |
.. sourcecode:: pycon |
| 551 |
|
| 552 |
>>> xslt_root = etree.XML('''\ |
| 553 |
... <xsl:stylesheet version="1.0" |
| 554 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
| 555 |
... <xsl:output method="text" encoding="utf8" /> |
| 556 |
... <xsl:template match="/"> |
| 557 |
... <foo><xsl:value-of select="/a/b/text()" /></foo> |
| 558 |
... </xsl:template> |
| 559 |
... </xsl:stylesheet>''') |
| 560 |
>>> transform = etree.XSLT(xslt_root) |
| 561 |
|
| 562 |
>>> result = transform(doc) |
| 563 |
>>> result.write_output("output.txt.gz", compression=9) # doctest: +SKIP |
| 564 |
|
| 565 |
.. |
| 566 |
>>> from io import BytesIO |
| 567 |
>>> out = BytesIO() |
| 568 |
>>> result.write_output(out) |
| 569 |
>>> data = out.getvalue() |
| 570 |
>>> b'Text' in data |
| 571 |
True |
| 572 |
|
| 573 |
|
| 574 |
Stylesheet parameters |
| 575 |
--------------------- |
| 576 |
|
| 577 |
It is possible to pass parameters, in the form of XPath expressions, to the |
| 578 |
XSLT template: |
| 579 |
|
| 580 |
.. sourcecode:: pycon |
| 581 |
|
| 582 |
>>> xslt_tree = etree.XML('''\ |
| 583 |
... <xsl:stylesheet version="1.0" |
| 584 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
| 585 |
... <xsl:param name="a" /> |
| 586 |
... <xsl:template match="/"> |
| 587 |
... <foo><xsl:value-of select="$a" /></foo> |
| 588 |
... </xsl:template> |
| 589 |
... </xsl:stylesheet>''') |
| 590 |
>>> transform = etree.XSLT(xslt_tree) |
| 591 |
>>> doc_root = etree.XML('<a><b>Text</b></a>') |
| 592 |
|
| 593 |
The parameters are passed as keyword parameters to the transform call. |
| 594 |
First, let's try passing in a simple integer expression: |
| 595 |
|
| 596 |
.. sourcecode:: pycon |
| 597 |
|
| 598 |
>>> result = transform(doc_root, a="5") |
| 599 |
>>> bytes(result) |
| 600 |
b'<?xml version="1.0"?>\n<foo>5</foo>\n' |
| 601 |
|
| 602 |
You can use any valid XPath expression as parameter value: |
| 603 |
|
| 604 |
.. sourcecode:: pycon |
| 605 |
|
| 606 |
>>> result = transform(doc_root, a="/a/b/text()") |
| 607 |
>>> bytes(result) |
| 608 |
b'<?xml version="1.0"?>\n<foo>Text</foo>\n' |
| 609 |
|
| 610 |
It's also possible to pass an XPath object as a parameter: |
| 611 |
|
| 612 |
.. sourcecode:: pycon |
| 613 |
|
| 614 |
>>> result = transform(doc_root, a=etree.XPath("/a/b/text()")) |
| 615 |
>>> bytes(result) |
| 616 |
b'<?xml version="1.0"?>\n<foo>Text</foo>\n' |
| 617 |
|
| 618 |
Passing a string expression looks like this: |
| 619 |
|
| 620 |
.. sourcecode:: pycon |
| 621 |
|
| 622 |
>>> result = transform(doc_root, a="'A'") |
| 623 |
>>> bytes(result) |
| 624 |
b'<?xml version="1.0"?>\n<foo>A</foo>\n' |
| 625 |
|
| 626 |
To pass a string that (potentially) contains quotes, you can use the |
| 627 |
``.strparam()`` class method. Note that it does not escape the |
| 628 |
string. Instead, it returns an opaque object that keeps the string |
| 629 |
value. |
| 630 |
|
| 631 |
.. sourcecode:: pycon |
| 632 |
|
| 633 |
>>> plain_string_value = etree.XSLT.strparam( |
| 634 |
... """ It's "Monty Python" """) |
| 635 |
>>> result = transform(doc_root, a=plain_string_value) |
| 636 |
>>> bytes(result) |
| 637 |
b'<?xml version="1.0"?>\n<foo> It\'s "Monty Python" </foo>\n' |
| 638 |
|
| 639 |
If you need to pass parameters that are not legal Python identifiers, |
| 640 |
pass them inside of a dictionary: |
| 641 |
|
| 642 |
.. sourcecode:: pycon |
| 643 |
|
| 644 |
>>> transform = etree.XSLT(etree.XML('''\ |
| 645 |
... <xsl:stylesheet version="1.0" |
| 646 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
| 647 |
... <xsl:param name="non-python-identifier" /> |
| 648 |
... <xsl:template match="/"> |
| 649 |
... <foo><xsl:value-of select="$non-python-identifier" /></foo> |
| 650 |
... </xsl:template> |
| 651 |
... </xsl:stylesheet>''')) |
| 652 |
|
| 653 |
>>> result = transform(doc_root, **{'non-python-identifier': '5'}) |
| 654 |
>>> bytes(result) |
| 655 |
b'<?xml version="1.0"?>\n<foo>5</foo>\n' |
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
Errors and messages |
| 660 |
------------------- |
| 661 |
|
| 662 |
Like most of the processing oriented objects in lxml.etree, ``XSLT`` |
| 663 |
provides an error log that lists messages and error output from the |
| 664 |
last run. See the `parser documentation`_ for a description of the |
| 665 |
error log. |
| 666 |
|
| 667 |
.. _`parser documentation`: parsing.html#error-log |
| 668 |
|
| 669 |
.. sourcecode:: pycon |
| 670 |
|
| 671 |
>>> xslt_root = etree.XML('''\ |
| 672 |
... <xsl:stylesheet version="1.0" |
| 673 |
... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
| 674 |
... <xsl:template match="/"> |
| 675 |
... <xsl:message terminate="no">STARTING</xsl:message> |
| 676 |
... <foo><xsl:value-of select="/a/b/text()" /></foo> |
| 677 |
... <xsl:message terminate="no">DONE</xsl:message> |
| 678 |
... </xsl:template> |
| 679 |
... </xsl:stylesheet>''') |
| 680 |
>>> transform = etree.XSLT(xslt_root) |
| 681 |
|
| 682 |
>>> doc_root = etree.XML('<a><b>Text</b></a>') |
| 683 |
>>> result = transform(doc_root) |
| 684 |
>>> bytes(result) |
| 685 |
b'<?xml version="1.0"?>\n<foo>Text</foo>\n' |
| 686 |
|
| 687 |
>>> print(transform.error_log) |
| 688 |
<string>:0:0:ERROR:XSLT:ERR_OK: STARTING |
| 689 |
<string>:0:0:ERROR:XSLT:ERR_OK: DONE |
| 690 |
|
| 691 |
>>> for entry in transform.error_log: |
| 692 |
... print('message from line %s, col %s: %s' % ( |
| 693 |
... entry.line, entry.column, entry.message)) |
| 694 |
... print('domain: %s (%d)' % (entry.domain_name, entry.domain)) |
| 695 |
... print('type: %s (%d)' % (entry.type_name, entry.type)) |
| 696 |
... print('level: %s (%d)' % (entry.level_name, entry.level)) |
| 697 |
... print('filename: %s' % entry.filename) |
| 698 |
message from line 0, col 0: STARTING |
| 699 |
domain: XSLT (22) |
| 700 |
type: ERR_OK (0) |
| 701 |
level: ERROR (2) |
| 702 |
filename: <string> |
| 703 |
message from line 0, col 0: DONE |
| 704 |
domain: XSLT (22) |
| 705 |
type: ERR_OK (0) |
| 706 |
level: ERROR (2) |
| 707 |
filename: <string> |
| 708 |
|
| 709 |
Note that there is no way in XSLT to distinguish between user |
| 710 |
messages, warnings and error messages that occurred during the |
| 711 |
run. ``libxslt`` simply does not provide this information. You can |
| 712 |
partly work around this limitation by making your own messages |
| 713 |
uniquely identifiable, e.g. with a common text prefix. |
| 714 |
|
| 715 |
|
| 716 |
The ``xslt()`` tree method |
| 717 |
-------------------------- |
| 718 |
|
| 719 |
There's also a convenience method on ElementTree objects for doing XSL |
| 720 |
transformations. This is less efficient if you want to apply the same XSL |
| 721 |
transformation to multiple documents, but is shorter to write for one-shot |
| 722 |
operations, as you do not have to instantiate a stylesheet yourself: |
| 723 |
|
| 724 |
.. sourcecode:: pycon |
| 725 |
|
| 726 |
>>> result = doc.xslt(xslt_tree, a="'A'") |
| 727 |
>>> bytes(result) |
| 728 |
b'<?xml version="1.0"?>\n<foo>A</foo>\n' |
| 729 |
|
| 730 |
This is a shortcut for the following code: |
| 731 |
|
| 732 |
.. sourcecode:: pycon |
| 733 |
|
| 734 |
>>> transform = etree.XSLT(xslt_tree) |
| 735 |
>>> result = transform(doc, a="'A'") |
| 736 |
>>> bytes(result) |
| 737 |
b'<?xml version="1.0"?>\n<foo>A</foo>\n' |
| 738 |
|
| 739 |
|
| 740 |
Dealing with stylesheet complexity |
| 741 |
---------------------------------- |
| 742 |
|
| 743 |
Some applications require a larger set of rather diverse stylesheets. |
| 744 |
lxml.etree allows you to deal with this in a number of ways. Here are |
| 745 |
some ideas to try. |
| 746 |
|
| 747 |
The most simple way to reduce the diversity is by using XSLT |
| 748 |
parameters that you pass at call time to configure the stylesheets. |
| 749 |
The ``partial()`` function in the ``functools`` module |
| 750 |
may come in handy here. It allows you to bind a set of keyword |
| 751 |
arguments (i.e. stylesheet parameters) to a reference of a callable |
| 752 |
stylesheet. The same works for instances of the ``XPath()`` |
| 753 |
evaluator, obviously. |
| 754 |
|
| 755 |
You may also consider creating stylesheets programmatically. Just |
| 756 |
create an XSL tree, e.g. from a parsed template, and then add or |
| 757 |
replace parts as you see fit. Passing an XSL tree into the ``XSLT()`` |
| 758 |
constructor multiple times will create independent stylesheets, so |
| 759 |
later modifications of the tree will not be reflected in the already |
| 760 |
created stylesheets. This makes stylesheet generation very straightforward. |
| 761 |
|
| 762 |
A third thing to remember is the support for `custom extension |
| 763 |
functions`_ and `XSLT extension elements`_. Some things are much |
| 764 |
easier to express in XSLT than in Python, while for others it is the |
| 765 |
complete opposite. Finding the right mixture of Python code and XSL |
| 766 |
code can help a great deal in keeping applications well designed and |
| 767 |
maintainable. |
| 768 |
|
| 769 |
|
| 770 |
Profiling |
| 771 |
--------- |
| 772 |
|
| 773 |
If you want to know how your stylesheet performed, pass the ``profile_run`` |
| 774 |
keyword to the transform: |
| 775 |
|
| 776 |
.. sourcecode:: pycon |
| 777 |
|
| 778 |
>>> result = transform(doc, a="/a/b/text()", profile_run=True) |
| 779 |
>>> profile = result.xslt_profile |
| 780 |
|
| 781 |
The value of the ``xslt_profile`` property is an ElementTree with profiling |
| 782 |
data about each template, similar to the following: |
| 783 |
|
| 784 |
.. sourcecode:: xml |
| 785 |
|
| 786 |
<profile> |
| 787 |
<template rank="1" match="/" name="" mode="" calls="1" time="1" average="1"/> |
| 788 |
</profile> |
| 789 |
|
| 790 |
Note that this is a read-only document. You must not move any of its elements |
| 791 |
to other documents. Please deep-copy the document if you need to modify it. |
| 792 |
If you want to free it from memory, just do: |
| 793 |
|
| 794 |
.. sourcecode:: pycon |
| 795 |
|
| 796 |
>>> del result.xslt_profile |