I am trying to use <xsl:sort>
to sort the animals by the atrribute @animalName in the XML file bellow, while using <xsl:apply-templates>
to display the animals in a table but it does not seem to work. Any suggestions?
The XML file
<animal animalName="Giraffe" animalId="No. 9">
<animalNamesInfo scientificName="Giraffa camelopardalis"> </animalNamesInfo>
</animal>
<animal animalName="Chimopanzee" animalId="No. 7" >
<animalNamesInfo scientificName="Pan troglodytes"> </animalNamesInfo>
</animal>
<animal animalName="Zebra" animalId="No. 6" >
<animalNamesInfo scientificName="Equus quagga bοehmi"> </animalNamesInfo>
</animal>
And the xsl code
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<BODY>
<table border="5">
<th>animal_name</th>
<th>scientific_name</th>
<xsl:apply-templates select="//animal"/>
<xsl:sort select = "@animalName" />
</table>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="animal">
<tr>
<td><xsl:value-of select="@animalName"/></td>
<td><xsl:value-of select="animalNamesInfo/@scientificName"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
CodePudding user response:
This is due to a minor grammar error: xsl:sort
has to be a child of xsl:apply-templates
. So change this part to
<xsl:template match="/">
<HTML>
<BODY>
<table border="5">
<th>animal_name</th>
<th>scientific_name</th>
<xsl:apply-templates select="//animal">
<xsl:sort select = "@animalName" />
</xsl:apply-templates>
</table>
</BODY>
</HTML>
</xsl:template>
and then, everything should work fine.