extensions.txt 19 KB

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