extensions.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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(dummy, a):
  43. ... return "Hello %s" % a
  44. >>> def ola(dummy, a):
  45. ... return "Ola %s" % a
  46. >>> def loadsofargs(dummy, *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('world')"))
  69. Hello world
  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. ... entries = list(context.eval_context.items())
  126. ... entries.sort()
  127. ... print(entries)
  128. >>> ns["print_context"] = print_context
  129. >>> ignore = root.xpath("//*[pt:print_context()]")
  130. [('a', 'done')]
  131. [('a', 'done'), ('b', 'done')]
  132. Evaluators and XSLT
  133. -------------------
  134. Extension functions work for all ways of evaluating XPath expressions and for
  135. XSL transformations:
  136. .. sourcecode:: pycon
  137. >>> e = etree.XPathEvaluator(doc)
  138. >>> print(e('es:hello(local-name(/a))'))
  139. Ola a
  140. >>> namespaces = {'f' : 'http://mydomain.org/myfunctions'}
  141. >>> e = etree.XPathEvaluator(doc, namespaces=namespaces)
  142. >>> print(e('f:hello(local-name(/a))'))
  143. Hello a
  144. >>> xslt = etree.XSLT(etree.XML('''
  145. ... <stylesheet version="1.0"
  146. ... xmlns="http://www.w3.org/1999/XSL/Transform"
  147. ... xmlns:es="http://mydomain.org/myother/functions">
  148. ... <output method="text" encoding="ASCII"/>
  149. ... <template match="/">
  150. ... <value-of select="es:hello(string(//b))"/>
  151. ... </template>
  152. ... </stylesheet>
  153. ... '''))
  154. >>> print(xslt(doc))
  155. Ola Haegar
  156. It is also possible to register namespaces with a single evaluator after its
  157. creation. While the following example involves no functions, the idea should
  158. still be clear:
  159. .. sourcecode:: pycon
  160. >>> f = StringIO('<a xmlns="http://mydomain.org/myfunctions" />')
  161. >>> ns_doc = etree.parse(f)
  162. >>> e = etree.XPathEvaluator(ns_doc)
  163. >>> e('/a')
  164. []
  165. This returns nothing, as we did not ask for the right namespace. When we
  166. register the namespace with the evaluator, however, we can access it via a
  167. prefix:
  168. .. sourcecode:: pycon
  169. >>> e.register_namespace('foo', 'http://mydomain.org/myfunctions')
  170. >>> e('/foo:a')[0].tag
  171. '{http://mydomain.org/myfunctions}a'
  172. Note that this prefix mapping is only known to this evaluator, as opposed to
  173. the global mapping of the FunctionNamespace objects:
  174. .. sourcecode:: pycon
  175. >>> e2 = etree.XPathEvaluator(ns_doc)
  176. >>> e2('/foo:a')
  177. Traceback (most recent call last):
  178. ...
  179. lxml.etree.XPathEvalError: Undefined namespace prefix
  180. Evaluator-local extensions
  181. --------------------------
  182. Apart from the global registration of extension functions, there is also a way
  183. of making extensions known to a single Evaluator or XSLT. All evaluators and
  184. the XSLT object accept a keyword argument ``extensions`` in their constructor.
  185. The value is a dictionary mapping (namespace, name) tuples to functions:
  186. .. sourcecode:: pycon
  187. >>> extensions = {('local-ns', 'local-hello') : hello}
  188. >>> namespaces = {'l' : 'local-ns'}
  189. >>> e = etree.XPathEvaluator(doc, namespaces=namespaces, extensions=extensions)
  190. >>> print(e('l:local-hello(string(b))'))
  191. Hello Haegar
  192. For larger numbers of extension functions, you can define classes or modules
  193. and use the ``Extension`` helper:
  194. .. sourcecode:: pycon
  195. >>> class MyExt:
  196. ... def function1(self, _, arg):
  197. ... return '1'+arg
  198. ... def function2(self, _, arg):
  199. ... return '2'+arg
  200. ... def function3(self, _, arg):
  201. ... return '3'+arg
  202. >>> ext_module = MyExt()
  203. >>> functions = ('function1', 'function2')
  204. >>> extensions = etree.Extension( ext_module, functions, ns='local-ns' )
  205. >>> e = etree.XPathEvaluator(doc, namespaces=namespaces, extensions=extensions)
  206. >>> print(e('l:function1(string(b))'))
  207. 1Haegar
  208. The optional second argument to ``Extension`` can either be be a
  209. sequence of names to select from the module, a dictionary that
  210. explicitly maps function names to their XPath alter-ego or ``None``
  211. (explicitly passed) to take all available functions under their
  212. original name (if their name does not start with '_').
  213. The additional ``ns`` keyword argument takes a namespace URI or
  214. ``None`` (also if left out) for the default namespace. The following
  215. examples will therefore all do the same thing:
  216. .. sourcecode:: pycon
  217. >>> functions = ('function1', 'function2', 'function3')
  218. >>> extensions = etree.Extension( ext_module, functions )
  219. >>> e = etree.XPathEvaluator(doc, extensions=extensions)
  220. >>> print(e('function1(function2(function3(string(b))))'))
  221. 123Haegar
  222. >>> extensions = etree.Extension( ext_module, functions, ns=None )
  223. >>> e = etree.XPathEvaluator(doc, extensions=extensions)
  224. >>> print(e('function1(function2(function3(string(b))))'))
  225. 123Haegar
  226. >>> extensions = etree.Extension(ext_module)
  227. >>> e = etree.XPathEvaluator(doc, extensions=extensions)
  228. >>> print(e('function1(function2(function3(string(b))))'))
  229. 123Haegar
  230. >>> functions = {
  231. ... 'function1' : 'function1',
  232. ... 'function2' : 'function2',
  233. ... 'function3' : 'function3'
  234. ... }
  235. >>> extensions = etree.Extension(ext_module, functions)
  236. >>> e = etree.XPathEvaluator(doc, extensions=extensions)
  237. >>> print(e('function1(function2(function3(string(b))))'))
  238. 123Haegar
  239. For convenience, you can also pass a sequence of extensions:
  240. .. sourcecode:: pycon
  241. >>> extensions1 = etree.Extension(ext_module)
  242. >>> extensions2 = etree.Extension(ext_module, ns='local-ns')
  243. >>> e = etree.XPathEvaluator(doc, extensions=[extensions1, extensions2],
  244. ... namespaces=namespaces)
  245. >>> print(e('function1(l:function2(function3(string(b))))'))
  246. 123Haegar
  247. What to return from a function
  248. ------------------------------
  249. .. _`XPath return values`: xpathxslt.html#xpath-return-values
  250. Extension functions can return any data type for which there is an XPath
  251. equivalent (see the documentation on `XPath return values`). This includes
  252. numbers, boolean values, elements and lists of elements. Note that integers
  253. will also be returned as floats:
  254. .. sourcecode:: pycon
  255. >>> def returnsFloat(_):
  256. ... return 1.7
  257. >>> def returnsInteger(_):
  258. ... return 1
  259. >>> def returnsBool(_):
  260. ... return True
  261. >>> def returnFirstNode(_, nodes):
  262. ... return nodes[0]
  263. >>> ns = etree.FunctionNamespace(None)
  264. >>> ns['float'] = returnsFloat
  265. >>> ns['int'] = returnsInteger
  266. >>> ns['bool'] = returnsBool
  267. >>> ns['first'] = returnFirstNode
  268. >>> e = etree.XPathEvaluator(doc)
  269. >>> e("float()")
  270. 1.7
  271. >>> e("int()")
  272. 1.0
  273. >>> int( e("int()") )
  274. 1
  275. >>> e("bool()")
  276. True
  277. >>> e("count(first(//b))")
  278. 1.0
  279. As the last example shows, you can pass the results of functions back into
  280. the XPath expression. Elements and sequences of elements are treated as
  281. XPath node-sets:
  282. .. sourcecode:: pycon
  283. >>> def returnsNodeSet(_):
  284. ... results1 = etree.Element('results1')
  285. ... etree.SubElement(results1, 'result').text = "Alpha"
  286. ... etree.SubElement(results1, 'result').text = "Beta"
  287. ...
  288. ... results2 = etree.Element('results2')
  289. ... etree.SubElement(results2, 'result').text = "Gamma"
  290. ... etree.SubElement(results2, 'result').text = "Delta"
  291. ...
  292. ... results3 = etree.SubElement(results2, 'subresult')
  293. ... return [results1, results2, results3]
  294. >>> ns['new-node-set'] = returnsNodeSet
  295. >>> e = etree.XPathEvaluator(doc)
  296. >>> r = e("new-node-set()/result")
  297. >>> print([ t.text for t in r ])
  298. ['Alpha', 'Beta', 'Gamma', 'Delta']
  299. >>> r = e("new-node-set()")
  300. >>> print([ t.tag for t in r ])
  301. ['results1', 'results2', 'subresult']
  302. >>> print([ len(t) for t in r ])
  303. [2, 3, 0]
  304. >>> r[0][0].text
  305. 'Alpha'
  306. >>> etree.tostring(r[0])
  307. b'<results1><result>Alpha</result><result>Beta</result></results1>'
  308. >>> etree.tostring(r[1])
  309. b'<results2><result>Gamma</result><result>Delta</result><subresult/></results2>'
  310. >>> etree.tostring(r[2])
  311. b'<subresult/>'
  312. The current implementation deep-copies newly created elements in node-sets.
  313. Only the elements and their children are passed on, no outlying parents or
  314. tail texts will be available in the result. This also means that in the above
  315. example, the `subresult` elements in `results2` and `results3` are no longer
  316. identical within the node-set, they belong to independent trees:
  317. .. sourcecode:: pycon
  318. >>> print("%s - %s" % (r[1][-1].tag, r[2].tag))
  319. subresult - subresult
  320. >>> print(r[1][-1] == r[2])
  321. False
  322. >>> print(r[1][-1].getparent().tag)
  323. results2
  324. >>> print(r[2].getparent())
  325. None
  326. This is an implementation detail that you should be aware of, but you should
  327. avoid relying on it in your code. Note that elements taken from the source
  328. document (the most common case) do not suffer from this restriction. They
  329. will always be passed unchanged.
  330. XSLT extension elements
  331. =======================
  332. Just like the XPath extension functions described above, lxml supports
  333. custom extension *elements* in XSLT. This means, you can write XSLT
  334. code like this:
  335. .. sourcecode:: xml
  336. <xsl:template match="*">
  337. <my:python-extension>
  338. <some-content />
  339. </my:python-extension>
  340. </xsl:template>
  341. And then you can implement the element in Python like this:
  342. .. sourcecode:: pycon
  343. >>> class MyExtElement(etree.XSLTExtension):
  344. ... def execute(self, context, self_node, input_node, output_parent):
  345. ... print("Hello from XSLT!")
  346. ... output_parent.text = "I did it!"
  347. ... # just copy own content input to output
  348. ... output_parent.extend( list(self_node) )
  349. The arguments passed to the ``.execute()`` method are
  350. context
  351. The opaque evaluation context. You need this when calling back
  352. into the XSLT processor.
  353. self_node
  354. A read-only Element object that represents the extension element
  355. in the stylesheet.
  356. input_node
  357. The current context Element in the input document (also read-only).
  358. output_parent
  359. The current insertion point in the output document. You can
  360. append elements or set the text value (not the tail). Apart from
  361. that, the Element is read-only.
  362. Declaring extension elements
  363. ----------------------------
  364. In XSLT, extension elements can be used like any other XSLT element,
  365. except that they must be declared as extensions using the standard
  366. XSLT ``extension-element-prefixes`` option:
  367. .. sourcecode:: pycon
  368. >>> xslt_ext_tree = etree.XML('''
  369. ... <xsl:stylesheet version="1.0"
  370. ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  371. ... xmlns:my="testns"
  372. ... extension-element-prefixes="my">
  373. ... <xsl:template match="/">
  374. ... <foo><my:ext><child>XYZ</child></my:ext></foo>
  375. ... </xsl:template>
  376. ... <xsl:template match="child">
  377. ... <CHILD>--xyz--</CHILD>
  378. ... </xsl:template>
  379. ... </xsl:stylesheet>''')
  380. To register the extension, add its namespace and name to the extension
  381. mapping of the XSLT object:
  382. .. sourcecode:: pycon
  383. >>> my_extension = MyExtElement()
  384. >>> extensions = { ('testns', 'ext') : my_extension }
  385. >>> transform = etree.XSLT(xslt_ext_tree, extensions = extensions)
  386. Note how we pass an instance here, not the class of the extension.
  387. Now we can run the transformation and see how our extension is
  388. called:
  389. .. sourcecode:: pycon
  390. >>> root = etree.XML('<dummy/>')
  391. >>> result = transform(root)
  392. Hello from XSLT!
  393. >>> str(result)
  394. '<?xml version="1.0"?>\n<foo>I did it!<child>XYZ</child></foo>\n'
  395. Applying XSL templates
  396. ----------------------
  397. XSLT extensions are a very powerful feature that allows you to
  398. interact directly with the XSLT processor. You have full read-only
  399. access to the input document and the stylesheet, and you can even call
  400. back into the XSLT processor to process templates. Here is an example
  401. that passes an Element into the ``.apply_templates()`` method of the
  402. ``XSLTExtension`` instance:
  403. .. sourcecode:: pycon
  404. >>> class MyExtElement(etree.XSLTExtension):
  405. ... def execute(self, context, self_node, input_node, output_parent):
  406. ... child = self_node[0]
  407. ... results = self.apply_templates(context, child)
  408. ... output_parent.append(results[0])
  409. >>> my_extension = MyExtElement()
  410. >>> extensions = { ('testns', 'ext') : my_extension }
  411. >>> transform = etree.XSLT(xslt_ext_tree, extensions = extensions)
  412. >>> root = etree.XML('<dummy/>')
  413. >>> result = transform(root)
  414. >>> str(result)
  415. '<?xml version="1.0"?>\n<foo><CHILD>--xyz--</CHILD></foo>\n'
  416. Note how we applied the templates to a child of the extension element
  417. itself, i.e. to an element inside the stylesheet instead of an element
  418. of the input document.
  419. Working with read-only elements
  420. -------------------------------
  421. There is one important thing to keep in mind: all Elements that the
  422. ``execute()`` method gets to deal with are read-only Elements, so you
  423. cannot modify them. They also will not easily work in the API. For
  424. example, you cannot pass them to the ``tostring()`` function or wrap
  425. them in an ``ElementTree``.
  426. What you can do, however, is to deepcopy them to make them normal
  427. Elements, and then modify them using the normal etree API. So this
  428. will work:
  429. .. sourcecode:: pycon
  430. >>> from copy import deepcopy
  431. >>> class MyExtElement(etree.XSLTExtension):
  432. ... def execute(self, context, self_node, input_node, output_parent):
  433. ... child = deepcopy(self_node[0])
  434. ... child.text = "NEW TEXT"
  435. ... output_parent.append(child)
  436. >>> my_extension = MyExtElement()
  437. >>> extensions = { ('testns', 'ext') : my_extension }
  438. >>> transform = etree.XSLT(xslt_ext_tree, extensions = extensions)
  439. >>> root = etree.XML('<dummy/>')
  440. >>> result = transform(root)
  441. >>> str(result)
  442. '<?xml version="1.0"?>\n<foo><child>NEW TEXT</child></foo>\n'