Handling Multiple Selections with xsl:for-each

Handling Multiple Selections with xsl:for-each

The select attribute selects only the first node that matches its selection criterion. However, what if you have multiple nodes that could match? For example, say you can have multiple < NAME > elements for each planet:

 <PLANET>  <NAME>Mercury</NAME>   <NAME>Closest planet to the sun</NAME>  <MASS UNITS="(Earth = 1)">.0553</MASS>     <DAY UNITS="days">58.65</DAY>     <RADIUS UNITS="miles">1516</RADIUS>     <DENSITY UNITS="(Earth = 1)">.983</DENSITY>     <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion--> </PLANET> 

The <xsl:value-of> element's select attribute by itself selects only the first <NAME> element. To loop over all possible matches, you can use the <xsl:for-each> element, like this:

Listing ch13_08.xsl
 <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">     <xsl:template match="PLANETS">         <HTML>             <xsl:apply-templates/>         </HTML>     </xsl:template> <xsl:template match="PLANET">  <xsl:for-each select="NAME">   <P>   <xsl:value-of select="."/>   </P>   </xsl:for-each>  </xsl:template> </xsl:stylesheet> 

This stylesheet catches all <NAME> elements, places their values in a <P> element, and adds them to the output document, like this:

 <HTML>      <P>Mercury</P> <P>Closest planet to the sun</P>     <P>Venus</P>     <P>Earth</P> </HTML> 

We've seen now that you can use the match and select attributes to indicate what nodes you want to work with. The actual syntax that you can use with these attributes is fairly complex but worth knowing. I'll take a look at the match attribute in more detail first, and I'll examine the select attribute later in this chapter.



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net