XSLT Tutorial
Worksheet 5: xsl:if
Open the the following Headlines XML
found in the Worksheet_5 directory. :
<headlines>
<article>Rescued penguins swim home
<summary>Some 150
penguins unaffected ...</summary>
<category>Science
& Nature</category>
</article>
<article>Bug mops up sewage
<summary>A bug found in sewage water
has...</summary>
<category>Science &
Nature</category>
</article>
<article>In the land of the colour-blind
<summary>A hunt to find the cause of widespread
...</summary>
<category>Health</category>
</article>
</headlines>
Objective: Open the todaysnews.xsl in
your Transformation tool. In the following XSLT, we want to find
every second article and output it in blue. So we test the XPath
function, position(), if the mod() XPath function returns an integer >
0 (therefore every odd article), then output this:
<xsl:template
match="/headlines"> <html><basefont face=
"Verdana"size="2"/><body>
<h2>Today's Headlines</h2>
<xsl:for-each
select="article" >
<xsl:if test="position() mod 2 > 0">
<font color="blue"><xsl:value-of
select="text()"/></font><br/>
</xsl:if>
</xsl:for-each>
</body></html>
</xsl:template>
The HTML result is:
Today's Headlines
Rescued penguins swim home
In the land of the colour-blind
Q: Why has the <xsl:value-of
select="text()"/> been used, when you normally use
<xsl:value-of select="."/>
A: Once again to stress this point,
the "." actually chooses a
node-set, instead of just outputting the text of the element.
Up until now we have been using "." where the element has had
no child nodes. Try changing this example to use "." - you
will notice that it inserts all the text of the node itself and its
child nodes. The text() function specifically outputs only
the text of the element, instead of the complete node-set.
Q: mod??
A: The mod XPath function divides one value
(position()) by another value (2). It then returns the integer of
the remainder. Which is:
7 divided by 2 = 3 with a remainder of 1
mod returns 1
This is a great way to find odd and even values.
|