<xsl:for-each>

XSLT Function: <xsl:for-each>The XSLT <xsl:for-each> element is used to iterate over XML nodes as defined by an expression in the select attribute.

The expression defined in the mandatory select attribute is either an XPATH expression or a variable reference pointing to a node set in the source document.

An error will result if the expression defined in the select attribute points to an element and not a node set.

Refer to the <xsl:sort> element if sorting / ordering is required when iterating over the node set.


Syntax


<xsl:for-each select="expression" />

where expression is either an XPATH expression or an XSLT variable reference.

Attributes

namemandatory/optionaldescription
selectMANDATORYan XPATH expression or variable reference to a node set.

Examples

For our examples we are using the fictional library as an input XML. Any XSL transform examples we define uses this XML as an input:

<?xml version="1.0" encoding="UTF-8"?>
<library>
<category name="dogs">
<book>
<name>All about dogs</name>
<author>Someone</author>
<isin>true</isin>
<daysuntilreturn>0</daysuntilreturn>
</book>
<book>
<name>Spots on dogs</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>02</daysuntilreturn>
</book>
<book>
<name>Bark like me</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>05</daysuntilreturn>
</book>
</category>
<category name="cats">
<book>
<name>All about cats</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>3</daysuntilreturn>
</book>
<book>
<name>Meoww</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>03</daysuntilreturn>
</book>
</category>
</library>

How to iterate over XML nodes

The following XSL transform selects all the books in our library and outputs the book names in the order they are encountered.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<books>
<xsl:for-each select="/library/category/book">
<item><xsl:value-of select="./name"/></item>
</xsl:for-each>
</books>
</xsl:template>
</xsl:stylesheet>

The results of the above XSL transform outputs the book names as follows:

<?xml version="1.0" encoding="UTF-8"?>
<books>
<item>All about dogs</item>
<item>Spots on dogs</item>
<item>Bark like me</item>
<item>All about cats</item>
<item>Meoww</item>
</books>

Posted in XSLT and tagged .

Leave a Reply