I'd like to define an ordering on strings used in a certain element. For example, <class>Senior</class> <class>Junior</class> <class>Sophomore</class> <class>Freshman<class> would describe a reasonable ordering on class.
Is there a way using <xsl:sort select='class'> that would sort by the ordering given above?
Thanks in advance.
Have you looked into Saxon's custom collation extensions?
For example,
This uses the RuleBasedCollator format from the Java class of that name.
To use it in your sort (piggybacking on Tim C's useful example input XML and stylesheet):
This gives the same results as Tim C's solution. (Tested using Saxon PE 9.3.0.5.)
It's not an xsl:function, but it gives you a little more flexibility than an array, and is arguably more succinct. AFAICT there is no way to create a custom collation using an XSLT user-defined function. Since you don't say why you want an
xsl:function
, it's hard to speculate on what alternatives will meet your needs.For complete xsl:function-like flexibility, you could define your own collator in Java; see http://www.saxonica.com/documentation/extensibility/collation.xml on implementing the java.util.Comparator interface and specifying your comparator in the
class
attribute.What you could do in your XSLT is define a variable to represent your custom ordering, like so
Then to access this 'array' you can define another variable to reference the XSLT document itself:
This now allows you to look up the sort attribute for a given class name when you are sorting (where current() represents the current node being sorted)
As an example, here is the full XSLT
When you apply this to the following sample XML...
The following is returned