Web Services, Part V: XML and XSLT Programming: Implementing Conditional Statements - Doc JavaScript
Web Services, Part V: XML and XSLT Programming
Implementing Conditional Statements
XSLT supports conditional statements. It is based on a very special construct which includes three XSL tags: xsl:choose
, xsl:where
, and xsl:otherwise
. The <xsl:choose>
and </xsl:choose>
are the outer tag pair. They embrace the where
tags, <xsl:where>
and </xsl:where>
, followed by the pair <xsl:otherwise>
and </xsl:otherwise>
.
MyDVD Rental Store
's report according to their magnitude. We want them red
if they are below the weekly sales quota, green
otherwise. The following section chooses the style
attribute for one <td>
cell in a table. The XML data we compare is dvds_rented
, and the limit is weekly_quota
:
<td> <xsl:attribute name="style"> <xsl:choose> <xsl:when test="number(@dvds_rented <= $weekly_quota)"> color:red;</xsl:when> <xsl:otherwise>color:green;</xsl:otherwise> </xsl:choose> text-align:right; </xsl:attribute> <xsl:value-of select="format-number(@dvds_rented, '###,###')"/> </td>
Here is the complete XSLT file that converts the MyDVD XML file (try it)(view it):
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl=" https://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/> <xsl:param name="forecast" select="50000"/> <xsl:param name="weekly_quota" select="12000"/> <xsl:template match="/"> <HTML> <HEAD> <TITLE><xsl:value-of select="//summary/heading"/></TITLE> </HEAD> <BODY> <H1><xsl:value-of select="//summary/heading"/></H1> <H2><xsl:value-of select="//summary/subhead"/></H2> <P><xsl:value-of select="//summary/description"/></P> <TABLE> <TR> <TH>Month\Week</TH> <xsl:for-each select="//data/month[1]/week"> <TH>W<xsl:value-of select="@number"/></TH> </xsl:for-each> <TH>Total</TH> <TH>Forecast</TH> </TR> <xsl:for-each select="//data/month"> <tr> <th style="text-align:left"><xsl:value-of select="name"/></th> <xsl:for-each select="week"> <td> <xsl:attribute name="style"> <xsl:choose> <xsl:when test="number(@dvds_rented <= $weekly_quota)"> color:red;</xsl:when> <xsl:otherwise>color:green;</xsl:otherwise> </xsl:choose> text-align:right; </xsl:attribute> <xsl:value-of select="format-number(@dvds_rented, '###,###')"/> </td> </xsl:for-each> <td style="text-align:right;font-weight:bold"> <xsl:value-of select="format-number(sum(week/@dvds_rented), '###,###')"/> </td> <td style="text-align:right;font-weight:bold"> <xsl:value-of select="format-number($forecast, '###,###')"/> </td> </tr> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template> </xsl:stylesheet>
You should get something like this in the output:
Next: A Final Word
Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: December 31, 2001
Revised: December 31, 2001
URL: https://www.webreference.com/js/column100/9.html