Defining Conditional Templates Using <xsl:choose>
The <xsl:choose>
element provides a mechanism for either/or processing: <xsl:choose>
contains a series of <xsl:when>
elements that are tested in order from top to bottom until a match is found. An <xsl:otherwise>
element can be used to insert a template if no match is found.
The following code can be added to the example in the previous topic to color-code the rows by price. Rows 0-25 are displayed in green, rows 25-50 are displayed in blue, and rows 50 and higher are displayed in red. The color is changed by conditionally generating a portion of the value of the STYLE
attribute on the table row.
<TR> <xsl:attribute name="STYLE">color: <xsl:choose> <xsl:when test="price[. < 25]">green</xsl:when> <xsl:when test="price[. < 50]">blue</xsl:when> <xsl:otherwise>red</xsl:otherwise> </xsl:choose> </xsl:attribute> <TD>
Example
This example uses an XML source file and an XSLT style sheet.
XML File (portfolio-choose.xml)
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="portfolio-choose.xsl"?> <portfolio xmlns:dt="urn:schemas-microsoft-com:datatypes" xml:space="preserve"> <stock exchange="nyse"> <name>zacx corp</name> <symbol>ZCXM</symbol> <price dt:dt="number">28.875</price> </stock> <stock exchange="nasdaq"> <name>zaffymat inc</name> <symbol>ZFFX</symbol> <price dt:dt="number">92.250</price> </stock> <stock exchange="nasdaq"> <name>zysmergy inc</name> <symbol>ZYSZ</symbol> <price dt:dt="number">20.313</price> </stock> </portfolio>
XSLT File (portfolio-choose.xsl)
<?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML> <BODY> <TABLE BORDER="2"> <TR> <TD>Symbol</TD> <TD>Name</TD> <TD>Price</TD> </TR> <xsl:for-each select="portfolio/stock"> <TR> <xsl:attribute name="STYLE">color: <xsl:choose> <xsl:when test="price[. < 25]">green</xsl:when> <xsl:when test="price[. < 50]">blue</xsl:when> <xsl:otherwise>red</xsl:otherwise> </xsl:choose> </xsl:attribute> <TD> <xsl:value-of select="symbol"/> <xsl:if test="@exchange[.='nasdaq']">*</xsl:if> </TD> <TD><xsl:value-of select="name"/></TD> <TD><xsl:value-of select="price"/></TD> </TR> </xsl:for-each> </TABLE> <P>* Listed on Nasdaq stock exchange</P> <P>Price key: <SPAN STYLE="color:green">less than 25</SPAN>, <SPAN STYLE="color:blue">25-50</SPAN>, <SPAN STYLE="color:red">50+</SPAN>.</P> </BODY> </HTML> </xsl:template> </xsl:stylesheet>
Formatted Output