sortingreversexpath-3.1

XPath 3.1 fn:sort order descending


Sorting with XPath 3.1 uses fn:sort(), with up to 3 parameters (target, collation, function). The question is about the definition and use of the function parameter, which bubbles-up the sort key, how should reverse (descending) sort, on the given key and collation, should be done/handled?

I found no example nor explanation. This sort function seems fairly sophisticated, it would be surprising that it does not handle reverse sorting. But how does it?

Regards.


Solution

  • The function itself allows you to provide a sort key, if that is numeric you can of course reverse the sorting by using the negation function($item) { -$item/value }.

    For other options see Dimitre's answer.

    Note that progress in ongoing to develop XPath 4 and XQuery 4 and XSLT 4, the current state is that for XPath 4 fn:sort https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort is extended to allow an additional fourth argument with a sequence of values ascending or descending to indicate how the sort for each key returned by the third argument, the key function, is supposed to be ordered.

    BaseX (XQuery processor that, with XPath functions being shared between XPath, XQuery and XSLT, and XPath being a subset of XQuery, already implements part of the 4 spec) already supports that fourth argument, see this online fidde example.