Tuesday, March 26, 2013

XSLT Key Function to Grouping xml nodes

XSLT key function returns a node-set that contains all the nodes in an XML document that match the name-value pair.

Syntax for the key() function is
<xsl:key name="name" match="pattern" use="expression"/>

Lets see one example for this. We have student details xml file with below mentioned values. In this we need to group the students based on the gender they belong. First we will look into the xml file

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xslt_key.xsl"?>
<STUDENTS>
<STUDENT Name="Azhar" Class="5" Gender="Male" Rank="5" />
<STUDENT Name="Yuvaraj" Class="6" Gender="Male" Rank="2" />
<STUDENT Name="Malar" Class="5" Gender="Female" Rank="5" />
<STUDENT Name="Kanmani" Class="7" Gender="Female" Rank="1" />
<STUDENT Name="Kathir" Class="6" Gender="Male" Rank="1" />
<STUDENT Name="Anbu" Class="7" Gender="Male" Rank="6" />
<STUDENT Name="Rose" Class="6" Gender="Female" Rank="5" />
<STUDENT Name="Merlyn" Class="5" Gender="Female" Rank="7" />
<STUDENT Name="Ganesh" Class="4" Gender="Male" Rank="2" />
</STUDENTS>
Now we will look into the xslt file to group the students based on the gender
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="html" omit-xml-declaration="yes" indent="yes" />
<xsl:key match="STUDENT" name="STUDENT_Gender" use="@Gender" />
<xsl:template match="STUDENTS">
<xsl:for-each select="STUDENT[generate-id(.)=generate-id(key('STUDENT_Gender', @Gender)[1])]">
<b><xsl:value-of select="concat(@Gender,' Students Details')"/></b>
<table border="1">
<tr>
<td>
<b><xsl:value-of select="'Name'"/></b>
</td>
<td>
<b><xsl:value-of select="'Class'"/></b>
</td>
<td>
<b><xsl:value-of select="'Rank'"/></b>
</td>
</tr>
<xsl:for-each select="key('STUDENT_Gender',@Gender)">
<tr>
<td>
<xsl:value-of select="@Name"/>1
</td>
<td>
<xsl:value-of select="@Class"/>
</td>
<td>
<xsl:value-of select="@Rank"/>
</td>
</tr>
</xsl:for-each>
</table>
<br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

No comments:

Post a Comment