I have to sort out the codes in numerical order.
The codes have four characters and four numerals.
for example,
COMP2100
COMP2400
COMP3410
LAWS2202
LAWS2250
when I just do <xsl:sort select="code" order="ascending" />
it displays above result.
However, I want that to be in ‘numerical order’ that is
COMP2100
LAWS2202
COMP2250
COMP2400
COMP3410
How do I do this?
Note: the OP has now provided sample XML. The below theories can be trivially adapted to this XML.
I. XSLT 1.0 (part 1)
Here is a simple solution that assumes your assertion (“the codes have four characters and four numerals”) will always be the case:
…is applied to an imagined XML document, shuffled into random order:
…the correct result is produced:
Explanation:
Identity Transform— one of the (if not the) most fundamental design patterns in XSLT — copies all nodes from the source XML document to the result XML document as-is.<t>based upon the characters in the string from position 5 to the string’s end.Again, note that this solution assumes your original assertion — “the codes have four characters and four numerals” — is (and always will be) true.
II. XSLT 1.0 (part 2)
A (potentially) safer solution would be to assume that there might be numerous non-numeric characters in various positions within the
<i>nodes. In that case, this XSLT:…provides the same result:
Explanation:
Identity Transformis once again used.Double Translate Method(first proposed by Michael Kay and first shown to me by Dimitre Novatchev) to remove all non-numeric characters from the value of each<i>element before sorting.III. XSLT 2.0 Solution
Here’s a possible XSLT 2.0 solution is very similar to part 2 of the XSLT 1.0 solution; it merely replaces the Double Translate Method with XPath 2.0’s ability to handle regular expressions:
Note that by no means are you required to use regular expressions in XPath 2.0; the Double Translate Method works just as well as in XPath 1.0. The
replace()method will, however, most likely be more efficient.