I have an XML structure which looks like this -
<Root>
<name rank = "1">ABC
<name rank ="1">BCD</name>
</name>
<name rank ="0">XYZ
<name rank ="1">BCD</name>
<name rank ="3">YYZ</name>
<name rank ="0">FEG</name>
<name rank ="0">DEG</name>
</name>
</Root>
I want to transform this XML by making a copy of it, preserving the hierarchy, and sort it in the order (1) By Rank (ascending) (2) If Ranks are equal, sort it by name(ascending)
After transformation, the structure should look like this.
<Root>
<name rank ="0">XYZ
<name rank ="0">DEG</name>
<name rank ="0">FEG</name>
<name rank ="1">BCD</name>
<name rank ="3">YYZ</name>
</name>
<name rank = "1">ABC
<name rank ="1">BCD</name>
</name>
</Root>
I have the following XSL, which does not preserve the heirarchy or gives me the correct sort. Can someone please help me out? This is my first time working with XSL and would appreciate any help or pointers in the right direction.
<xsl:template match="/*">
<xsl:copy>
<xsl:for-each select="//name">
<xsl:sort select="@rank" data-type="number" order="ascending"/>
<xsl:sort select="name" order="ascending" />
<xsl:copy-of select="."/>
</xsl:for-each>
</xsl:copy>
</xsl:template>
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Explanation:
Using two
xsl:sort
instructions. The priority of the sort operations corresponds to the document order of the respectivexsl:sort
instructions.