In this concluding article, expand your XSLT vocabulary by exploring conditional constructs, loops, variables, and numbering, together with examples and illustrations of how these programming capabilities can substantially simplify your XSLT experience.
In addition to conditional tests, XSLT also allows for a primitive looping mechanism via the instruction. If both the source tree and result tree follow a defined structure, this instruction can go a long way towards making your XSLT stylesheets more efficient and compact.
The <xsl:for-each> instruction always comes with a "select" attribute, which is used to select a node collection for the template rule to act upon. Once the node collection has been obtained, the templates contained within the <xsl:for-each> instruction are applied to every node within the node collection.
If this sounds confusing - the following example should make things clearer. Consider the following XML document:
<?xml version="1.0"?>
<top_five>
<movie>
<name>Star Wars: A
New Hope</name>
<cast>Mark Hamill, Carrie Fisher, Harrison Ford</cast>
<director>George
Lucas</director>
<rank>1</rank>
</movie>
<movie>
<name>The
Patriot</name>
<cast>Mel Gibson, Heath Ledger, Jason Isaacs</cast>
<director>Roland
Emmerich</director>
<rank>5</rank>
</movie>
<movie>
<name>The
Whole Nine Yards</name>
<cast>Bruce Willis, Matthew Perry</cast>
<director>Jonathan
Lynn</director>
<rank>3</rank>
</movie>
<movie>
<name>Gladiator</name>
<cast>Russell
Crowe, Connie Nielsen, Joaquin Phoenix</cast>
<director>Ridley Scott</director>
<rank>4</rank>
</movie>
<movie>
<name>Unbreakable</name>
<cast>Bruce
Willis, Samuel L. Jackson</cast>
<director>M. Night Shyamalan</director>
<rank>2</rank>
</movie>
</top_five>
As you can see, this is pretty clearly-structured, with every movie an independent
entity within the document. This makes it perfect for a <xsl:for-each> loop.
Now, the loop will iterate as many times as there as "movie" elements in the
document, applying the template contained within its opening and closing tags on every iteration. Here's the resulting HTML output,
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<basefont
face="Arial" size="4">
</head>
<body>
<ol>
<li>Star Wars: A New
Hope</li>
<br>
<font size="2">Mark Hamill, Carrie Fisher, Harrison Ford
| George
Lucas</font>
<li>The Patriot</li>
<br>
<font size="2">Mel
Gibson, Heath Ledger, Jason Isaacs | Roland
Emmerich</font>
<li>The Whole
Nine Yards</li>
<br>
<font size="2">Bruce Willis, Matthew Perry | Jonathan
Lynn</font>
<li>Gladiator</li>
<br>
<font size="2">Russell Crowe,
Connie Nielsen, Joaquin Phoenix | Ridley
Scott</font>
<li>Unbreakable</li>
<br>
<font
size="2">Bruce Willis, Samuel L. Jackson | M. Night Shyamalan</font>
</ol>
</body>
</html>