How to import lxml xpath functions to default namespace?

时光总嘲笑我的痴心妄想 提交于 2019-12-12 15:55:51

问题


This is a example in lxml doc:

>>> regexpNS = "http://exslt.org/regular-expressions"
>>> find = etree.XPath("//*[re:test(., '^abc$', 'i')]",
...                    namespaces={'re':regexpNS})

>>> root = etree.XML("<root><a>aB</a><b>aBc</b></root>")
>>> print(find(root)[0].text)
aBc

I want to import re:test() function to default namespace, so that I can call it without prefix re:. How can I do it? Thanks!


回答1:


You can put a function in the empty function namespace:

functionNS = etree.FunctionNamespace(None)
functionNS['test'] = lambda context, nodes, *args: print(context, nodes, args)

By doing so, the new test function is already registered with the empty namespace prefix, that means you can use it like this:

root.xpath("//*[test(., 'arg1', 'arg2')]")

Unfortunately the function that is called for "{http://exslt.org/regular-expressions}test" isn't available from python, only from within the lxml extension implemented in C, so you can't simply assign it to functionNS['test'].

That means you'd need to reimplement it in python to assign it to the empty function namespace...

If that's not worth the trouble for you to spare you typing three characters, you could use this trick to make the re prefix for the namespace global:

etree.FunctionNamespace("http://exslt.org/regular-expressions").prefix = 're'

Then at least you don't need to pass the namespaces dict for each xpath expression.



来源:https://stackoverflow.com/questions/17292421/how-to-import-lxml-xpath-functions-to-default-namespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!