RE: [xsl] XSLT functions in XPath

Subject: RE: [xsl] XSLT functions in XPath
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Mon, 9 Oct 2006 19:55:01 +0100
> I am using the Saxon XPath implementation over DOM to take 
> advantage of the XPAth 2.0.
> This works really well most of the time (the time when I am 
> not missing anything), however I would like to have access to 
> two more functions which would be really helpful:
> 
> current()
> sort()
> 
> Is it somehow possible to use current() in "normal" XPath, an example:
> 
> contextA = //@isbn = '1234567'
> contextB = //author[books/book/@isbn = current() ] using contextA

Sadly, no. But you could switch from XPath to XQuery, which would allow you
to write:

   let $current := . return //author[books/book/@isbn = $current]

   for $x in expr order by $x/sortkey return $x

For the first one there's also a rather horrible workaround in XPath 2.0:

   for $current in . return //author[books/book/@isbn = $current]

But in my view it would be cleaner to bind a variable. It's not difficult:

final String isbn = "01234567890";
VariableResolver vr = new VariableResolver() {
    public Object resolveVariable(QName variableName) {
        if (variableName.getLocalPart().equals("isbn")) {
            return isbn;
        } else {
            return null;
        }
    }
};  

> Prior to Saxon I used Jaxen and wrote me an extension 
> function which could basically do something like
> 
> sort-by(//author, '@name', '@forename')
> or
> sort-by(//book, 'number(@year)')
> 
> Since Saxon has many more extension functions I wondered if I 
> could use the its XSLT functionality somehow for this task.

You could write such an extension function for Saxon, but there's none such
in the standard library.

But in Saxon's implementation of the JAXP XPath API, the XPathExpression
object has a method setSortKey() which allows you to get the results of the
expression in sorted order.

Sorting is a higher-order function so it's difficult to do as a pure
extension function, though Saxon has used this technique of supplying an
XPath expression in a string parameter in the past.

Michael Kay
http://www.saxonica.com/

Current Thread