The Open Source Swiss Army Knife

/xml/
/xml/ + sub-categories
http://www.sirfsup.com/
web directory content
    
      

Not logged in
Chat Register Login
return to:  http:/www.sirfsup.com      /xml 
Permalink: for_each.htm
Title: add
article options : please login   |  print view

<xsl:for-each>

<xsl:for-each> is a construct that processes an entire node set inside a single rule. <xsl:for-each> sets up a new context node set and context node internally that are useful for localized effects such as building formatted lists and calling special functions. For example, The rule uses <xsl:for-each> to create a numbered list of chapter titles before processing each chapter with the <xsl:apply-templates> directive. Thus, the following generates a table of contents:

<xsl:template match="book">
     <xsl:for-each select="chapter">
       <xsl:value-of select="position()"/>
       <xsl:value-of select="title"/>
     </xsl:for-each>
     <xsl:apply-templates/>
</xsl:template>

In this second example, we add filters to <xsl:for-each>. Here are the originals:

the xml filethe xsl file
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="foreach.xsl"?>
<catalog>
   <cd>
      <title>empire burlesque</title>
      <artist>bob dylan</artist>
      <country>usa</country>
      <company>columbia</company>
      <price>10.90</price>
      <year>1985</year>
   </cd>
</catalog>
<?xml version='1.0'?>
     <xsl:stylesheet xmlns:xsl="http://www.w3.org/tr/wd-xsl">
        <xsl:template match="/">
          <html>
          <body>
          <table border="2" bgcolor="yellow">
              <tr>
               <th>title</th>
               <th>artist</th>
              </tr>
              <xsl:for-each select="catalog/cd">
               <tr>
               <td><xsl:value-of select="title"/></td>
               <td><xsl:value-of select="artist"/></td>
               </tr>
              </xsl:for-each>
           </table>
           </body>
           </html>
         </xsl:template>
      </xsl:stylesheet>
try it out

To filter the XML file, simply add a filter to the select attribute in your for-each element in your XSL file.

Legal filter operators are:

  • =  (equal)
  • != (not equal)
  • &lt; less than
  • &gt; greater than

the combination is:

<xsl:for-each select="CATALOG/CD[ARTIST='Bob Dylan']">

The new slightly adjusted XSL stylesheet:

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
 <html>
 <body>
  <table border="2" bgcolor="yellow">
   <tr>
    <th>Title</th>
    <th>Artist</th>
   </tr>
   <xsl:for-each select="CATALOG/CD[ARTIST='Bob Dylan']">
   <tr>
    <td><xsl:value-of select="TITLE"/></td>
    <td><xsl:value-of select="ARTIST"/></td>
   </tr>
   </xsl:for-each>
  </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

Leave a Reply
Your Name:     anonymous
Your Email:
Website:  
Comments:

The author will be notified of your reply.
return to top