Given the following XML:
<?xml version="1.0"?>
<Things>
<Thing>
<Thing ID="0002"/>
<Name>Bob</Name>
</Thing>
<Thing>
<Thing ID="0003"/>
<Name>Alice</Name>
</Thing>
<Thing>
<Thing ID="0001"/>
<Name>Carol</Name>
</Thing>
</Things>
I want to output the same XML sorted by the ID attribute. The following stylesheet does what I want. The commented-out xsl:sort (and several variations that I tried) doesn’t work — I just get an unsorted copy of the original document. (And no error messages.)
How can I specifically select the ID attribute on the Thing element (to avoid using ID attributes on other elements that may be present in a larger document)?
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Things">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="*/@ID" data-type="number"/>
<!-- I don't understand why this doesn't work:
<xsl:sort select="Thing/Thing[@ID]" data-type="number"/>
-->
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
You want
At the point where this occurs, the context is already at each first-level
Thing, so the sort key is the @ID attribute of the second-level Thing.