Pages

Looping in XSLT

Using XSLT we can implement a loop using a xsl:for_each element.

As an example, consider this XML, that should be used for an electronic version of a "guess what I am" game:

<?xml version="1.0" encoding="UTF-8"?>
<Objects>
<Object name="Car">
<Characteristic>Hard</Characteristic>
<Characteristic>Shiny</Characteristic>
<Characteristic>Has 4 wheels</Characteristic>
<Characteristic>Internal Combustion Engine</Characteristic>
</Object>
</Objects>

From this give XML we want to extract such an HTML:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Object Characteristics</title>
</head>
<body>
<h3>Characteristics of Car</h3>
<ul>
<li>Hard</li>
<li>Shiny</li>
<li>Has 4 wheels</li>
<li>Internal Combustion Engine</li>
</ul>
</body>
</html>

To do that, in our XSLT we would pass the Object element to a template, and there we want to iterate an all its Characteristic element:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="/">
<html>
<head>
<title>Object Characteristics</title>
</head>
<body>
<h3>Characteristics of <xsl:value-of select="Objects/Object/@name"/></h3>
<xsl:apply-templates select="/Objects/Object"/>
</body>
</html>
</xsl:template>

<xsl:template match="Object">
<ul>
<xsl:for-each select="Characteristic">
<li>
<xsl:value-of select="."/>
</li>
</xsl:for-each>
</ul>
</xsl:template>

</xsl:stylesheet>

More information on XSLT and Saxon in chapter eight of Beginning XML by David Hunter et al. (Wrox).

No comments:

Post a Comment