Applies a template repeatedly to a set of nodes. Effectively applies whatever commands (template specifications) contained with the foreach loop as a method operating on the collection elements looped through by the foreach loop.
<xsl:for-each order-by="sort-criteria-list" select="pattern">
xsl:for-each iterates or loops into a collection. Note that the collection objects within the loop can be looped with another xsl:for-loop.
The example below shows iteration through a loop contained within a loop within a loop. The first foreach loop iterates through countries, the second through states within countries and the third within cities within states. Note how each successive loop does not have to parse for what its enwrapping loop parse for. Each loop provides each enclosed loop with its iterative object. In other words when we parse for cities we parse for cities/city within states/state and not world/countries/country/states/state/cities/city.
Click here to see the XML structure of this example.
Click here to see the XSL formatted display of this example.
<?xml version="1.0"?> <HTML xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <BODY STYLE="font-family:Arial, helvetica, sans-serif; font-size:12pt; background-color:#EEEEEE"> <H2>Cities</H2> <UL> <xsl:for-each select="world/countries/country"> <LI><FONT COLOR="red"><xsl:value-of select="name"/></FONT></LI> <UL> <xsl:for-each select="states/state"> <LI><FONT COLOR="green"><xsl:value-of select="name"/></FONT></LI> <UL> <xsl:for-each select="cities/city"> <LI><FONT COLOR="blue"><xsl:value-of select="name"/></FONT> is <xsl:value-of select="type"/></LI> </xsl:for-each> </UL> </xsl:for-each> </UL> </xsl:for-each> </UL> </BODY> </HTML>
<HTML> <BODY> <H2>Cities</H2> <UL> <LI><FONT COLOR="red">Canada</FONT></LI> <UL> <LI><FONT COLOR="green">Quebec</FONT></LI> <UL> <LI><FONT COLOR="blue">Montreal is French</FONT></LI> </UL> <LI><FONT COLOR="green">British Columbia</FONT></LI> <UL> <LI><FONT COLOR="blue">Vancouver is Nice</FONT></LI> </UL> </UL> <LI><FONT COLOR="red">United States</FONT></LI> <UL> <LI><FONT COLOR="green">New York</FONT></LI> <UL> <LI><FONT COLOR="blue">New York City is Commercial</FONT></LI> <LI><FONT COLOR="blue">Buffalo is Big Snow Balls</FONT></LI> </UL> <LI><FONT COLOR="green">California</FONT></LI> <UL> <LI><FONT COLOR="blue">San Francisco is Silicon Valley</FONT></LI> <LI><FONT COLOR="blue">Los Angeles is Polluted</FONT></LI> <LI><FONT COLOR="blue">San Diego is Sunny</FONT></LI> </UL> </UL> </UL> </BODY> </HTML>