问题描述:

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!

网友答案:

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.

相关阅读:
Top