Using xsl:if

Using xsl:if

You can make choices based on the input document using the <xsl:if> element. To use this element, you simply set its test attribute to an expression that evaluates to a Boolean value.

Here's an example. In this case, I'll list the planets one after the other and add a HTML horizontal rule, <HR> , element after the last elementbut only after the last element. I can do that with <xsl:if> like this:

Listing ch13_25.xsl
 <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="PLANETS">     <HTML>         <HEAD>             <TITLE>                 Planets             </TITLE>         </HEAD>         <BODY>             <xsl:apply-templates select="PLANET"/>         </BODY>     </HTML> </xsl:template> <xsl:template match="PLANET">     <P>     <xsl:value-of select="NAME"/>     is planet number <xsl:value-of select="position()"/> from the sun.     </P>  <xsl:if test="position() = last()"><xsl:element name="HR"/></xsl:if>  </xsl:template> </xsl:stylesheet> 

Here is the result; as you can see, the <HR> element appears after only the last planet has been listed:

 <HTML>  <HEAD> <TITLE>                 Planets             </TITLE> </HEAD> <BODY> <P>Mercury     is planet number 1 from the sun.     </P> <P>Venus     is planet number 2 from the sun.     </P> <P>Earth     is planet number 3 from the sun.     </P>  <HR>  </BODY> </HTML> 

You can see this result in Figure 13-5.

Figure 13-5. Using xsl:if .

graphics/13fig05.gif



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net