Working with xsl:choose in XSLT - Working with xsl:choose in XSLT: introduction
(Page 2 of 6 )
Now it is time to start “control flow” expressions within XSLT. The first construct I would like to concentrate on is “xsl:choose.”
The construct “xsl:choose” is very similar to the “select case” structure. You can have any number of conditions using “xsl:when” and finally you can have an “else” part using “xsl:otherwise.”
Let us work with a practical example. I would like to display all the employees along with salaries. I would also like to have salaries displayed in bold if they are above 3500. Now, there exists a condition to work with. Such types of conditions can be dealt with either by “xsl:choose” or “xsl:if” (based on the needs).
The following is the code which displays all employee details along with salaries in bold, if they are above 3500:
<?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 border="1">
<xsl:apply-templates select="SQLData/Rows" />
</table>
</xsl:template>
<xsl:template match="SQLData/Rows">
<tr>
<td>
<xsl:value-of select="Empno"/>
</td>
<td>
<xsl:value-of select="Ename"/>
</td>
<td>
<xsl:apply-templates select="Sal" />
</td>
<td>
<xsl:value-of select="Deptno"/>
</td>
</tr>
</xsl:template>
<xsl:template match="Sal">
<xsl:choose>
<xsl:when test="text() > '3500'">
<b>
<xsl:value-of select="."/>
</b>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Once the above is executed you are likely to get the following transformation:
<table border="1">
<tr>
<td>1001</td>
<td>Jag</td>
<td>
<b>4400</b>
</td>
<td>10</td>
</tr>
<tr>
<td>1002</td>
<td>Chat</td>
<td>2800</td>
<td>20</td>
</tr>
.
.
.
</table>
I excluded few of the lines for clarity. The next section will explain in detail the above XSLT code.
Next: Working with xsl:choose in XSLT: explanation >>
More ASP.NET Articles
More By Jagadish Chaterjee