|
|
XSL allows you to define templates that contain the constructs 'xsl:if,' <xsl:choose>,' and 'for-each' that correspond to 'if,' 'switch,' and 'for' loops, respectively. For example, the following fragment prints the string 'red' if the position of the current node is even:
<xsl:if> test="position()mod 2=0">red</xsl:if>
Unfortunately, there is no 'if-else' logic in XSL; instead, you need to use the <xsl:choose> construct. For example, the code fragment below displays the string 'red' if the position of the current node is even, otherwise it displays the string 'blue':
<xsl:variable name="color"> <xsl:choose> <xsl:when test="position()mod 2=0">red</xsl:when> <xsl:otherwise>blue</xsl:otherwise> </xsl:choose> </xsl:variable>
You can also assign the output of the previous fragment to a variable; the following example assigns the result of the <xsl:choose> logic to the variable 'color':
<xsl:variable name="color"> <xsl:choose> <xsl:when test="position()mod 2=0">red</xsl:when> <xsl:otherwise>blue</xsl:otherwise> </xsl:choose> </xsl:variable>
The <xsl:for-each> construct is very handy for processing a set of nodes. For example, the following code fragment displays the contents of the chapter <desc> elements:
<xsl:for-each select="/book/chapters/chapter"> <xsl:value-of select="./desc"/> </xsl:for-each>
|
|