Working with Expressions, Variables and xsl:for-each in XSLT - Working with xsl:for-each along with xsl:choose and xsl:template
(Page 4 of 6 )
Let us consider a business need which requires the display of all employee details along with employee salaries and grades. The grade of the employee is based on the salary. If the salary is above 3000, the employee belongs to the "high" grade; otherwise, he or she belongs to the "low" grade.
I would like to satisfy the above business need by using “for,” “choose” and a separate “template.” The following is the code to accomplish this task:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<table width="50%" cellspacing="0" cellpadding="0" style="font-
family:verdana;font-size:X-Small" border="1">
<tr bgcolor="#336699">
<th align="left">
<font color="White">ID</font>
</th>
<th align="right">
<font color="White">Name</font>
</th>
<th align="right">
<font color="White">Salary</font>
</th>
<th align="left">
<font color="White">Grade</font>
</th>
<th align="right">
<font color="White">Department</font>
</th>
</tr>
<xsl:for-each select="SQLData/Rows">
<tr>
<td align="left">
<xsl:value-
of select="Empno" />
</td>
<td align="left">
<xsl:value-
of select="Ename" />
</td>
<xsl:apply-templates select="Sal" />
<td align="right">
<xsl:value-
of select="Deptno" />
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
<xsl:template match="Sal">
<td align="right">
<xsl:value-of select="text()" />
</td>
<xsl:choose>
<xsl:when test="text() > '3000' ">
<td align="left">
high
</td>
</xsl:when>
<xsl:otherwise>
<td>
low
</td>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
When the above code gets executed, you are likely to get the following transformation:
<table width="50%" cellspacing="0" cellpadding="0" style="font-
family:verdana;font-size:X-Small" border="1">
<tr bgcolor="#336699">
<th align="left">
<font color="White">ID</font>
</th>
<th align="right">
<font color="White">Name</font>
</th>
<th align="right">
<font color="White">Salary</font>
</th>
<th align="left">
<font color="White">Grade</font>
</th>
<th align="right">
<font color="White">Department</font>
</th>
</tr>
<tr>
<td align="left">1001</td>
<td align="left">Jag</td>
<td align="right">4400</td>
<td align="left">
high
</td>
<td align="right">10</td>
</tr>
.
.
.
</table>
Next: Generating serial numbers when working with xsl:for-each >>
More ASP.NET Articles
More By Jagadish Chaterjee