Defining Conditional Templates Using <xsl:if>
The XML file in the example below contains portfolio data. The <stock>
element has an exchange
attribute. Suppose you want to generate some output only when this attribute has a certain value. You can create another row in the table, and put the attribute value in this row. Alternatively, you can indicate stocks from a particular exchange by noting them with an asterisk (*).
The <xsl:if>
element provides a mechanism for conditionally inserting structure into the output tree. In the following example, the <xsl:if>
element inserts an asterisk after the symbol for those stocks listed on the NASDAQ stock exchange. The contents of <xsl:if>
can be simple text, as in this example, or any structure allowed by XSLT, such as elements or attributes.
In the sample XSLT file below, the test
attribute takes a pattern. If the query described by the pattern selects one or more nodes, the <xsl:if>
template is inserted. If the selection is empty, the conditional is skipped. In this case, the query checks to see if the <stock>
element has an exchange
attribute. If so, the query then checks to see if the value of the exchange
attribute is equal to "nasdaq"
.
For more information about qualifying a pattern using brackets ([]) and constructing patterns that compare values, see Introduction to XPath Syntax.
Example
XML File (portfolio-if.xml)
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="portfolio-if.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-if.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> <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> </BODY> </HTML> </xsl:template> </xsl:stylesheet>
Formatted Output