如何将lxml xpath函数导入默认名称空间? [英] How to import lxml xpath functions to default namespace?
问题描述
这是 lxml文档中的示例:
>>> 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
我想将re:test()
函数导入默认名称空间,以便我可以在没有前缀re:
的情况下调用它.我该怎么做?谢谢!
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!
推荐答案
您可以将函数放在空函数名称空间中:
You can put a function in the empty function namespace:
functionNS = etree.FunctionNamespace(None)
functionNS['test'] = lambda context, nodes, *args: print(context, nodes, args)
这样做,新的test
函数已经用空的名称空间前缀注册,这意味着您可以像这样使用它:
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')]")
不幸的是,被称为的功能对于"{http://exslt.org/regular-expressions}test"
,它不能从python中获得,只能从用C实现的lxml扩展中获得,因此您不能简单地将其分配给functionNS['test']
.
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']
.
这意味着您需要在python中重新实现它,以将其分配给空函数名称空间...
That means you'd need to reimplement it in python to assign it to the empty function namespace...
如果不必为您省去键入三个字符的麻烦,则可以使用此技巧使名称空间的re
前缀变为全局:
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'
那么至少您不需要为每个xpath表达式传递名称空间dict.
Then at least you don't need to pass the namespaces dict for each xpath expression.
这篇关于如何将lxml xpath函数导入默认名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!