xpathxslt.txt 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. ========================
  2. XPath and XSLT with lxml
  3. ========================
  4. lxml supports XPath 1.0, XSLT 1.0 and the EXSLT extensions through
  5. libxml2 and libxslt in a standards compliant way.
  6. .. contents::
  7. ..
  8. 1 XPath
  9. 1.1 The ``xpath()`` method
  10. 1.2 Namespaces and prefixes
  11. 1.3 XPath return values
  12. 1.4 Generating XPath expressions
  13. 1.5 The ``XPath`` class
  14. 1.6 Regular expressions in XPath
  15. 1.7 The ``XPathEvaluator`` classes
  16. 1.8 ``ETXPath``
  17. 1.9 Error handling
  18. 2 XSLT
  19. 2.1 XSLT result objects
  20. 2.2 Stylesheet parameters
  21. 2.3 The ``xslt()`` tree method
  22. 2.4 Dealing with stylesheet complexity
  23. 2.5 Profiling
  24. The usual setup procedure:
  25. .. sourcecode:: pycon
  26. >>> from lxml import etree
  27. ..
  28. >>> try: from StringIO import StringIO
  29. ... except ImportError:
  30. ... from io import BytesIO
  31. ... def StringIO(s):
  32. ... if isinstance(s, str): s = s.encode("UTF-8")
  33. ... return BytesIO(s)
  34. >>> try: unicode = __builtins__["unicode"]
  35. ... except (NameError, KeyError): unicode = str
  36. XPath
  37. =====
  38. lxml.etree supports the simple path syntax of the `find, findall and
  39. findtext`_ methods on ElementTree and Element, as known from the original
  40. ElementTree library (ElementPath_). As an lxml specific extension, these
  41. classes also provide an ``xpath()`` method that supports expressions in the
  42. complete XPath syntax, as well as `custom extension functions`_.
  43. .. _ElementPath: http://effbot.org/zone/element-xpath.htm
  44. .. _`find, findall and findtext`: http://effbot.org/zone/element.htm#searching-for-subelements
  45. .. _`custom extension functions`: extensions.html#xpath-extension-functions
  46. .. _`XSLT extension elements`: extensions.html#xslt-extension-elements
  47. There are also specialized XPath evaluator classes that are more efficient for
  48. frequent evaluation: ``XPath`` and ``XPathEvaluator``. See the `performance
  49. comparison`_ to learn when to use which. Their semantics when used on
  50. Elements and ElementTrees are the same as for the ``xpath()`` method described
  51. here.
  52. .. _`performance comparison`: performance.html#xpath
  53. The ``xpath()`` method
  54. ----------------------
  55. For ElementTree, the xpath method performs a global XPath query against the
  56. document (if absolute) or against the root node (if relative):
  57. .. sourcecode:: pycon
  58. >>> f = StringIO('<foo><bar></bar></foo>')
  59. >>> tree = etree.parse(f)
  60. >>> r = tree.xpath('/foo/bar')
  61. >>> len(r)
  62. 1
  63. >>> r[0].tag
  64. 'bar'
  65. >>> r = tree.xpath('bar')
  66. >>> r[0].tag
  67. 'bar'
  68. When ``xpath()`` is used on an Element, the XPath expression is evaluated
  69. against the element (if relative) or against the root tree (if absolute):
  70. .. sourcecode:: pycon
  71. >>> root = tree.getroot()
  72. >>> r = root.xpath('bar')
  73. >>> r[0].tag
  74. 'bar'
  75. >>> bar = root[0]
  76. >>> r = bar.xpath('/foo/bar')
  77. >>> r[0].tag
  78. 'bar'
  79. >>> tree = bar.getroottree()
  80. >>> r = tree.xpath('/foo/bar')
  81. >>> r[0].tag
  82. 'bar'
  83. The ``xpath()`` method has support for XPath variables:
  84. .. sourcecode:: pycon
  85. >>> expr = "//*[local-name() = $name]"
  86. >>> print(root.xpath(expr, name = "foo")[0].tag)
  87. foo
  88. >>> print(root.xpath(expr, name = "bar")[0].tag)
  89. bar
  90. >>> print(root.xpath("$text", text = "Hello World!"))
  91. Hello World!
  92. Namespaces and prefixes
  93. -----------------------
  94. If your XPath expression uses namespace prefixes, you must define them
  95. in a prefix mapping. To this end, pass a dictionary to the
  96. ``namespaces`` keyword argument that maps the namespace prefixes used
  97. in the XPath expression to namespace URIs:
  98. .. sourcecode:: pycon
  99. >>> f = StringIO('''\
  100. ... <a:foo xmlns:a="http://codespeak.net/ns/test1"
  101. ... xmlns:b="http://codespeak.net/ns/test2">
  102. ... <b:bar>Text</b:bar>
  103. ... </a:foo>
  104. ... ''')
  105. >>> doc = etree.parse(f)
  106. >>> r = doc.xpath('/t:foo/b:bar',
  107. ... namespaces={'t': 'http://codespeak.net/ns/test1',
  108. ... 'b': 'http://codespeak.net/ns/test2'})
  109. >>> len(r)
  110. 1
  111. >>> r[0].tag
  112. '{http://codespeak.net/ns/test2}bar'
  113. >>> r[0].text
  114. 'Text'
  115. The prefixes you choose here are not linked to the prefixes used
  116. inside the XML document. The document may define whatever prefixes it
  117. likes, including the empty prefix, without breaking the above code.
  118. Note that XPath does not have a notion of a default namespace. The
  119. empty prefix is therefore undefined for XPath and cannot be used in
  120. namespace prefix mappings.
  121. There is also an optional ``extensions`` argument which is used to
  122. define `custom extension functions`_ in Python that are local to this
  123. evaluation. The namespace prefixes that they use in the XPath
  124. expression must also be defined in the namespace prefix mapping.
  125. XPath return values
  126. -------------------
  127. The return value types of XPath evaluations vary, depending on the
  128. XPath expression used:
  129. * True or False, when the XPath expression has a boolean result
  130. * a float, when the XPath expression has a numeric result (integer or float)
  131. * a 'smart' string (as described below), when the XPath expression has
  132. a string result.
  133. * a list of items, when the XPath expression has a list as result.
  134. The items may include Elements (also comments and processing
  135. instructions), strings and tuples. Text nodes and attributes in the
  136. result are returned as 'smart' string values. Namespace
  137. declarations are returned as tuples of strings: ``(prefix, URI)``.
  138. XPath string results are 'smart' in that they provide a
  139. ``getparent()`` method that knows their origin:
  140. * for attribute values, ``result.getparent()`` returns the Element
  141. that carries them. An example is ``//foo/@attribute``, where the
  142. parent would be a ``foo`` Element.
  143. * for the ``text()`` function (as in ``//text()``), it returns the
  144. Element that contains the text or tail that was returned.
  145. You can distinguish between different text origins with the boolean
  146. properties ``is_text``, ``is_tail`` and ``is_attribute``.
  147. Note that ``getparent()`` may not always return an Element. For
  148. example, the XPath functions ``string()`` and ``concat()`` will
  149. construct strings that do not have an origin. For them,
  150. ``getparent()`` will return None.
  151. There are certain cases where the smart string behaviour is
  152. undesirable. For example, it means that the tree will be kept alive
  153. by the string, which may have a considerable memory impact in the case
  154. that the string value is the only thing in the tree that is actually
  155. of interest. For these cases, you can deactivate the parental
  156. relationship using the keyword argument ``smart_strings``.
  157. .. sourcecode:: pycon
  158. >>> root = etree.XML("<root><a>TEXT</a></root>")
  159. >>> find_text = etree.XPath("//text()")
  160. >>> text = find_text(root)[0]
  161. >>> print(text)
  162. TEXT
  163. >>> print(text.getparent().text)
  164. TEXT
  165. >>> find_text = etree.XPath("//text()", smart_strings=False)
  166. >>> text = find_text(root)[0]
  167. >>> print(text)
  168. TEXT
  169. >>> hasattr(text, 'getparent')
  170. False
  171. Generating XPath expressions
  172. ----------------------------
  173. ElementTree objects have a method ``getpath(element)``, which returns a
  174. structural, absolute XPath expression to find that element:
  175. .. sourcecode:: pycon
  176. >>> a = etree.Element("a")
  177. >>> b = etree.SubElement(a, "b")
  178. >>> c = etree.SubElement(a, "c")
  179. >>> d1 = etree.SubElement(c, "d")
  180. >>> d2 = etree.SubElement(c, "d")
  181. >>> tree = etree.ElementTree(c)
  182. >>> print(tree.getpath(d2))
  183. /c/d[2]
  184. >>> tree.xpath(tree.getpath(d2)) == [d2]
  185. True
  186. The ``XPath`` class
  187. -------------------
  188. The ``XPath`` class compiles an XPath expression into a callable function:
  189. .. sourcecode:: pycon
  190. >>> root = etree.XML("<root><a><b/></a><b/></root>")
  191. >>> find = etree.XPath("//b")
  192. >>> print(find(root)[0].tag)
  193. b
  194. The compilation takes as much time as in the ``xpath()`` method, but it is
  195. done only once per class instantiation. This makes it especially efficient
  196. for repeated evaluation of the same XPath expression.
  197. Just like the ``xpath()`` method, the ``XPath`` class supports XPath
  198. variables:
  199. .. sourcecode:: pycon
  200. >>> count_elements = etree.XPath("count(//*[local-name() = $name])")
  201. >>> print(count_elements(root, name = "a"))
  202. 1.0
  203. >>> print(count_elements(root, name = "b"))
  204. 2.0
  205. This supports very efficient evaluation of modified versions of an XPath
  206. expression, as compilation is still only required once.
  207. Prefix-to-namespace mappings can be passed as second parameter:
  208. .. sourcecode:: pycon
  209. >>> root = etree.XML("<root xmlns='NS'><a><b/></a><b/></root>")
  210. >>> find = etree.XPath("//n:b", namespaces={'n':'NS'})
  211. >>> print(find(root)[0].tag)
  212. {NS}b
  213. Regular expressions in XPath
  214. ----------------------------
  215. By default, ``XPath`` supports regular expressions in the EXSLT_ namespace:
  216. .. sourcecode:: pycon
  217. >>> regexpNS = "http://exslt.org/regular-expressions"
  218. >>> find = etree.XPath("//*[re:test(., '^abc$', 'i')]",
  219. ... namespaces={'re':regexpNS})
  220. >>> root = etree.XML("<root><a>aB</a><b>aBc</b></root>")
  221. >>> print(find(root)[0].text)
  222. aBc
  223. .. _EXSLT: http://www.exslt.org/
  224. You can disable this with the boolean keyword argument ``regexp`` which
  225. defaults to True.
  226. The ``XPathEvaluator`` classes
  227. ------------------------------
  228. lxml.etree provides two other efficient XPath evaluators that work on
  229. ElementTrees or Elements respectively: ``XPathDocumentEvaluator`` and
  230. ``XPathElementEvaluator``. They are automatically selected if you use the
  231. XPathEvaluator helper for instantiation:
  232. .. sourcecode:: pycon
  233. >>> root = etree.XML("<root><a><b/></a><b/></root>")
  234. >>> xpatheval = etree.XPathEvaluator(root)
  235. >>> print(isinstance(xpatheval, etree.XPathElementEvaluator))
  236. True
  237. >>> print(xpatheval("//b")[0].tag)
  238. b
  239. This class provides efficient support for evaluating different XPath
  240. expressions on the same Element or ElementTree.
  241. ``ETXPath``
  242. -----------
  243. ElementTree supports a language named ElementPath_ in its ``find*()`` methods.
  244. One of the main differences between XPath and ElementPath is that the XPath
  245. language requires an indirection through prefixes for namespace support,
  246. whereas ElementTree uses the Clark notation (``{ns}name``) to avoid prefixes
  247. completely. The other major difference regards the capabilities of both path
  248. languages. Where XPath supports various sophisticated ways of restricting the
  249. result set through functions and boolean expressions, ElementPath only
  250. supports pure path traversal without nesting or further conditions. So, while
  251. the ElementPath syntax is self-contained and therefore easier to write and
  252. handle, XPath is much more powerful and expressive.
  253. lxml.etree bridges this gap through the class ``ETXPath``, which accepts XPath
  254. expressions with namespaces in Clark notation. It is identical to the
  255. ``XPath`` class, except for the namespace notation. Normally, you would
  256. write:
  257. .. sourcecode:: pycon
  258. >>> root = etree.XML("<root xmlns='ns'><a><b/></a><b/></root>")
  259. >>> find = etree.XPath("//p:b", namespaces={'p' : 'ns'})
  260. >>> print(find(root)[0].tag)
  261. {ns}b
  262. ``ETXPath`` allows you to change this to:
  263. .. sourcecode:: pycon
  264. >>> find = etree.ETXPath("//{ns}b")
  265. >>> print(find(root)[0].tag)
  266. {ns}b
  267. Error handling
  268. --------------
  269. lxml.etree raises exceptions when errors occur while parsing or evaluating an
  270. XPath expression:
  271. .. sourcecode:: pycon
  272. >>> find = etree.XPath("\\")
  273. Traceback (most recent call last):
  274. ...
  275. lxml.etree.XPathSyntaxError: Invalid expression
  276. lxml will also try to give you a hint what went wrong, so if you pass a more
  277. complex expression, you may get a somewhat more specific error:
  278. .. sourcecode:: pycon
  279. >>> find = etree.XPath("//*[1.1.1]")
  280. Traceback (most recent call last):
  281. ...
  282. lxml.etree.XPathSyntaxError: Invalid predicate
  283. During evaluation, lxml will emit an XPathEvalError on errors:
  284. .. sourcecode:: pycon
  285. >>> find = etree.XPath("//ns:a")
  286. >>> find(root)
  287. Traceback (most recent call last):
  288. ...
  289. lxml.etree.XPathEvalError: Undefined namespace prefix
  290. This works for the ``XPath`` class, however, the other evaluators (including
  291. the ``xpath()`` method) are one-shot operations that do parsing and evaluation
  292. in one step. They therefore raise evaluation exceptions in all cases:
  293. .. sourcecode:: pycon
  294. >>> root = etree.Element("test")
  295. >>> find = root.xpath("//*[1.1.1]")
  296. Traceback (most recent call last):
  297. ...
  298. lxml.etree.XPathEvalError: Invalid predicate
  299. >>> find = root.xpath("//ns:a")
  300. Traceback (most recent call last):
  301. ...
  302. lxml.etree.XPathEvalError: Undefined namespace prefix
  303. >>> find = root.xpath("\\")
  304. Traceback (most recent call last):
  305. ...
  306. lxml.etree.XPathEvalError: Invalid expression
  307. Note that lxml versions before 1.3 always raised an ``XPathSyntaxError`` for
  308. all errors, including evaluation errors. The best way to support older
  309. versions is to except on the superclass ``XPathError``.
  310. XSLT
  311. ====
  312. lxml.etree introduces a new class, lxml.etree.XSLT. The class can be
  313. given an ElementTree or Element object to construct an XSLT
  314. transformer:
  315. .. sourcecode:: pycon
  316. >>> xslt_root = etree.XML('''\
  317. ... <xsl:stylesheet version="1.0"
  318. ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  319. ... <xsl:template match="/">
  320. ... <foo><xsl:value-of select="/a/b/text()" /></foo>
  321. ... </xsl:template>
  322. ... </xsl:stylesheet>''')
  323. >>> transform = etree.XSLT(xslt_root)
  324. You can then run the transformation on an ElementTree document by simply
  325. calling it, and this results in another ElementTree object:
  326. .. sourcecode:: pycon
  327. >>> f = StringIO('<a><b>Text</b></a>')
  328. >>> doc = etree.parse(f)
  329. >>> result_tree = transform(doc)
  330. By default, XSLT supports all extension functions from libxslt and
  331. libexslt as well as Python regular expressions through the `EXSLT
  332. regexp functions`_. Also see the documentation on `custom extension
  333. functions`_, `XSLT extension elements`_ and `document resolvers`_.
  334. There is a separate section on `controlling access`_ to external
  335. documents and resources.
  336. .. _`EXSLT regexp functions`: http://www.exslt.org/regexp/
  337. .. _`document resolvers`: resolvers.html
  338. .. _`controlling access`: resolvers.html#i-o-access-control-in-xslt
  339. XSLT result objects
  340. -------------------
  341. The result of an XSL transformation can be accessed like a normal ElementTree
  342. document:
  343. .. sourcecode:: pycon
  344. >>> root = etree.XML('<a><b>Text</b></a>')
  345. >>> result = transform(root)
  346. >>> result.getroot().text
  347. 'Text'
  348. but, as opposed to normal ElementTree objects, can also be turned into an (XML
  349. or text) string by applying the str() function:
  350. .. sourcecode:: pycon
  351. >>> str(result)
  352. '<?xml version="1.0"?>\n<foo>Text</foo>\n'
  353. The result is always a plain string, encoded as requested by the
  354. ``xsl:output`` element in the stylesheet. If you want a Python unicode string
  355. instead, you should set this encoding to ``UTF-8`` (unless the `ASCII` default
  356. is sufficient). This allows you to call the builtin ``unicode()`` function on
  357. the result:
  358. .. sourcecode:: pycon
  359. >>> unicode(result)
  360. u'<?xml version="1.0"?>\n<foo>Text</foo>\n'
  361. You can use other encodings at the cost of multiple recoding. Encodings that
  362. are not supported by Python will result in an error:
  363. .. sourcecode:: pycon
  364. >>> xslt_tree = etree.XML('''\
  365. ... <xsl:stylesheet version="1.0"
  366. ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  367. ... <xsl:output encoding="UCS4"/>
  368. ... <xsl:template match="/">
  369. ... <foo><xsl:value-of select="/a/b/text()" /></foo>
  370. ... </xsl:template>
  371. ... </xsl:stylesheet>''')
  372. >>> transform = etree.XSLT(xslt_tree)
  373. >>> result = transform(doc)
  374. >>> unicode(result)
  375. Traceback (most recent call last):
  376. ...
  377. LookupError: unknown encoding: UCS4
  378. Stylesheet parameters
  379. ---------------------
  380. It is possible to pass parameters, in the form of XPath expressions, to the
  381. XSLT template:
  382. .. sourcecode:: pycon
  383. >>> xslt_tree = etree.XML('''\
  384. ... <xsl:stylesheet version="1.0"
  385. ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  386. ... <xsl:param name="a" />
  387. ... <xsl:template match="/">
  388. ... <foo><xsl:value-of select="$a" /></foo>
  389. ... </xsl:template>
  390. ... </xsl:stylesheet>''')
  391. >>> transform = etree.XSLT(xslt_tree)
  392. >>> doc_root = etree.XML('<a><b>Text</b></a>')
  393. The parameters are passed as keyword parameters to the transform call.
  394. First, let's try passing in a simple integer expression:
  395. .. sourcecode:: pycon
  396. >>> result = transform(doc_root, a="5")
  397. >>> str(result)
  398. '<?xml version="1.0"?>\n<foo>5</foo>\n'
  399. You can use any valid XPath expression as parameter value:
  400. .. sourcecode:: pycon
  401. >>> result = transform(doc_root, a="/a/b/text()")
  402. >>> str(result)
  403. '<?xml version="1.0"?>\n<foo>Text</foo>\n'
  404. It's also possible to pass an XPath object as a parameter:
  405. .. sourcecode:: pycon
  406. >>> result = transform(doc_root, a=etree.XPath("/a/b/text()"))
  407. >>> str(result)
  408. '<?xml version="1.0"?>\n<foo>Text</foo>\n'
  409. Passing a string expression looks like this:
  410. .. sourcecode:: pycon
  411. >>> result = transform(doc_root, a="'A'")
  412. >>> str(result)
  413. '<?xml version="1.0"?>\n<foo>A</foo>\n'
  414. To pass a string that (potentially) contains quotes, you can use the
  415. ``.strparam()`` class method. Note that it does not escape the
  416. string. Instead, it returns an opaque object that keeps the string
  417. value.
  418. .. sourcecode:: pycon
  419. >>> plain_string_value = etree.XSLT.strparam(
  420. ... """ It's "Monty Python" """)
  421. >>> result = transform(doc_root, a=plain_string_value)
  422. >>> str(result)
  423. '<?xml version="1.0"?>\n<foo> It\'s "Monty Python" </foo>\n'
  424. If you need to pass parameters that are not legal Python identifiers,
  425. pass them inside of a dictionary:
  426. .. sourcecode:: pycon
  427. >>> transform = etree.XSLT(etree.XML('''\
  428. ... <xsl:stylesheet version="1.0"
  429. ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  430. ... <xsl:param name="non-python-identifier" />
  431. ... <xsl:template match="/">
  432. ... <foo><xsl:value-of select="$non-python-identifier" /></foo>
  433. ... </xsl:template>
  434. ... </xsl:stylesheet>'''))
  435. >>> result = transform(doc_root, **{'non-python-identifier': '5'})
  436. >>> str(result)
  437. '<?xml version="1.0"?>\n<foo>5</foo>\n'
  438. Errors and messages
  439. -------------------
  440. Like most of the processing oriented objects in lxml.etree, ``XSLT``
  441. provides an error log that lists messages and error output from the
  442. last run. See the `parser documentation`_ for a description of the
  443. error log.
  444. .. _`parser documentation`: parsing.html#error-log
  445. .. sourcecode:: pycon
  446. >>> xslt_root = etree.XML('''\
  447. ... <xsl:stylesheet version="1.0"
  448. ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  449. ... <xsl:template match="/">
  450. ... <xsl:message terminate="no">STARTING</xsl:message>
  451. ... <foo><xsl:value-of select="/a/b/text()" /></foo>
  452. ... <xsl:message terminate="no">DONE</xsl:message>
  453. ... </xsl:template>
  454. ... </xsl:stylesheet>''')
  455. >>> transform = etree.XSLT(xslt_root)
  456. >>> doc_root = etree.XML('<a><b>Text</b></a>')
  457. >>> result = transform(doc_root)
  458. >>> str(result)
  459. '<?xml version="1.0"?>\n<foo>Text</foo>\n'
  460. >>> print(transform.error_log)
  461. <string>:0:0:ERROR:XSLT:ERR_OK: STARTING
  462. <string>:0:0:ERROR:XSLT:ERR_OK: DONE
  463. >>> for entry in transform.error_log:
  464. ... print('message from line %s, col %s: %s' % (
  465. ... entry.line, entry.column, entry.message))
  466. ... print('domain: %s (%d)' % (entry.domain_name, entry.domain))
  467. ... print('type: %s (%d)' % (entry.type_name, entry.type))
  468. ... print('level: %s (%d)' % (entry.level_name, entry.level))
  469. ... print('filename: %s' % entry.filename)
  470. message from line 0, col 0: STARTING
  471. domain: XSLT (22)
  472. type: ERR_OK (0)
  473. level: ERROR (2)
  474. filename: <string>
  475. message from line 0, col 0: DONE
  476. domain: XSLT (22)
  477. type: ERR_OK (0)
  478. level: ERROR (2)
  479. filename: <string>
  480. Note that there is no way in XSLT to distinguish between user
  481. messages, warnings and error messages that occurred during the
  482. run. ``libxslt`` simply does not provide this information. You can
  483. partly work around this limitation by making your own messages
  484. uniquely identifiable, e.g. with a common text prefix.
  485. The ``xslt()`` tree method
  486. --------------------------
  487. There's also a convenience method on ElementTree objects for doing XSL
  488. transformations. This is less efficient if you want to apply the same XSL
  489. transformation to multiple documents, but is shorter to write for one-shot
  490. operations, as you do not have to instantiate a stylesheet yourself:
  491. .. sourcecode:: pycon
  492. >>> result = doc.xslt(xslt_tree, a="'A'")
  493. >>> str(result)
  494. '<?xml version="1.0"?>\n<foo>A</foo>\n'
  495. This is a shortcut for the following code:
  496. .. sourcecode:: pycon
  497. >>> transform = etree.XSLT(xslt_tree)
  498. >>> result = transform(doc, a="'A'")
  499. >>> str(result)
  500. '<?xml version="1.0"?>\n<foo>A</foo>\n'
  501. Dealing with stylesheet complexity
  502. ----------------------------------
  503. Some applications require a larger set of rather diverse stylesheets.
  504. lxml.etree allows you to deal with this in a number of ways. Here are
  505. some ideas to try.
  506. The most simple way to reduce the diversity is by using XSLT
  507. parameters that you pass at call time to configure the stylesheets.
  508. The ``partial()`` function in the ``functools`` module of Python 2.5
  509. may come in handy here. It allows you to bind a set of keyword
  510. arguments (i.e. stylesheet parameters) to a reference of a callable
  511. stylesheet. The same works for instances of the ``XPath()``
  512. evaluator, obviously.
  513. You may also consider creating stylesheets programmatically. Just
  514. create an XSL tree, e.g. from a parsed template, and then add or
  515. replace parts as you see fit. Passing an XSL tree into the ``XSLT()``
  516. constructor multiple times will create independent stylesheets, so
  517. later modifications of the tree will not be reflected in the already
  518. created stylesheets. This makes stylesheet generation very straight
  519. forward.
  520. A third thing to remember is the support for `custom extension
  521. functions`_ and `XSLT extension elements`_. Some things are much
  522. easier to express in XSLT than in Python, while for others it is the
  523. complete opposite. Finding the right mixture of Python code and XSL
  524. code can help a great deal in keeping applications well designed and
  525. maintainable.
  526. Profiling
  527. ---------
  528. If you want to know how your stylesheet performed, pass the ``profile_run``
  529. keyword to the transform:
  530. .. sourcecode:: pycon
  531. >>> result = transform(doc, a="/a/b/text()", profile_run=True)
  532. >>> profile = result.xslt_profile
  533. The value of the ``xslt_profile`` property is an ElementTree with profiling
  534. data about each template, similar to the following:
  535. .. sourcecode:: xml
  536. <profile>
  537. <template rank="1" match="/" name="" mode="" calls="1" time="1" average="1"/>
  538. </profile>
  539. Note that this is a read-only document. You must not move any of its elements
  540. to other documents. Please deep-copy the document if you need to modify it.
  541. If you want to free it from memory, just do:
  542. .. sourcecode:: pycon
  543. >>> del result.xslt_profile