Is there a way in XPath 3.1 (not XQuery) to sort the results?

437 Views Asked by At

I've looked through the spec and can't find anything. But I thought sorting was supported in 3.1.

Update (sorry, I have a tendency to assume people can read my mind and I don't list enough details):

We're doing this in Java so we call:

XPathCompiler.compile(query);
XPathExecutable.load()

So our query is normally "/root/employees/employee" to get a list of all employees (from Southwind.xml).

To put it in SQL-ish terms, we then want to give our users the ability to do something like this:

"/root/employees/employee order by lastname descending, firstname ascending".

Based on the answer below, how do I pass this in Java code? I see this example, but that I don't think is Java code (if it is, I don't understand the syntax).

And, can it sort on multiple nodes (ie sort on firstname if lastnames are equal)?

Put in a more detailed question with sample code here.

1

There are 1 best solutions below

1
On

Yes, see fn:sort in XPath and XQuery Functions and Operators 3.1:

Summary

Sorts a supplied sequence, based on the value of a sort key supplied as a function.

Signatures

fn:sort($input as item()*) as item()*

fn:sort($input as item()*, $collation as xs:string?) as item()*

fn:sort($input     as item()*,
        $collation as xs:string?,
        $key       as function(item()) as xs:anyAtomicType*) as item()*

[...]

Examples

The expression fn:sort((1, 4, 6, 5, 3)) returns (1, 3, 4, 5, 6).

[...]