Looping in XSLT

Contact Us or call 1-877-932-8228
Looping in XSLT

Looping in XSLT

The tag for looping in XSLT is <xsl:for-each>. It takes the select attribute, which uses XPath to point to a node-set and it outputs the contents of the xsl:for-each one time for each node in the set.

Code Sample:

FlowControl/Demos/BeatlesForEach.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
	<html>
		<head>
			<title>Beatles</title>
		</head>
		<body>
			<table border="1">
			<xsl:for-each select="beatles/beatle">
				<tr>
				<td><a href="{@link}"><xsl:value-of select="name/lastname"/></a></td>
				<td><a href="{@link}"><xsl:value-of select="name/firstname"/></a></td>
				</tr>
			</xsl:for-each>
			</table>
		</body>
	</html>
</xsl:template>

</xsl:stylesheet>

In the code above, you will also notice that the Beatles' first and last names are made into links. The value of the href attribute of the <a> tag is {@link}. This is the equivalent of <xsl:value-of select="@link"/>. However, it would not be well-formed XML to place the <xsl:value-of /> tag (or any tag, for that matter) inside the angle brackets of another open tag, so the curly-bracket syntax is used instead. The output in a browser would look like this.Output in Browser

Next