xpath regular expressions example?

Sam Ruby rubys at intertwingly.net
Fri Apr 18 04:44:21 EST 2008


Mary Gardiner wrote:
> When Sam first described the xpath-sifter filter, one of the advantages
> people talked about was the ability to use regular expressions in the
> filters. Is this in fact possible? I know XPath 2.0 introduces regular
> expressions, but I can't figure out if or how to use the matches()
> function.
> 
> Something like this does not work:
> 
> require:
>   //atom:title[matches(.,'Release')]
> 
> I get the following Python error:
> 
> ERROR:planet.runner:xmlXPathCompOpEval: function matches not found
> Unregistered function
> xmlXPathEval: 3 object left on the stack

Apparently, libxslt only supports XSLT 1.0.

   http://www.xmlsoft.org/XSLT.html

In your case, something like contains would suffice:

   http://www.w3.org/TR/xpath#function-contains

As near as I can tell, if you require the full power of regular 
expressions, something like the following would be required:

   import libxml2, re
   doc = libxml2.parseDoc(sys.stdin.read())
   xp = doc.xpathNewContext()
   xp.xpathRegisterNs("atom", "http://www.w3.org/2005/Atom")
   title = xp.xpathEval("/atom:entry/atom:title")
   if re.search('Release', title.content): print doc

- Sam Ruby



More information about the devel mailing list