- Use the <xsl:copy> to copy nodes
- Use the <xsl:sort> to sort node sets
- (select attribute specifies what to sort on)
For example: Sort the animal elements by leg number in (animals.xml)
XML Input file:
<?xml version="1.0"?>
<animals>
<animal name="dog" class="mammal" legs="4"/>
<animal name="shark" class="fish" legs="0"/>
<animal name="chicken" class="bird" legs="2"/>
</animals>
XML Output file:
<?xml version="1.0"?>
<animals>
<animal name="shark" class="fish" legs="0"/>
<animal name="chicken" class="bird" legs="2"/>
<animal name="dog" class="mammal" legs="4"/>
</animals>
XSL Style Sheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="text()">
</xsl:template>
<xsl:template match="animals">
<animals>
<xsl:apply-templates>
<xsl:sort data-type="number" select="@legs"/>
</xsl:apply-templates>
</animals>
</xsl:template>
<xsl:template match="animal">
<xsl:copy>
<xsl:apply-templates select="* | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="* | @*">
<xsl:copy>
<xsl:apply-templates select="* | @*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>