René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

XSL: Enumerating chapters

The xsl:for-each construct can be used to iterate over a node set:
The XML File:
<?xml version="1.0"?>
<book>

     <chapter>
       <para>one</para>
       <para>two</para>
       <para>three</para>
       <para>four</para>
     </chapter>
  
     <chapter>
       <para>eins</para>
       <para>zwei</para>
     </chapter>
  
     <chapter>
       <para>apple</para>
     </chapter>
  
     <chapter>
       <para>anna</para>
       <para>bob</para>
       <para>claude</para>
       <para>david</para>
       <para>emilia</para>
     </chapter>

     <chapter>
       <para>large</para>
       <para>small</para>
       <para>medium</para>
     </chapter>
  
     <chapter>
       <para>here</para>
       <para>there</para>
       <para>everywhere</para>
     </chapter>

     <chapter>
       <para>large</para>
       <para>small</para>
       <para>medium</para>
     </chapter>
  
     <chapter>
       <para>what</para>
       <para>when</para>
     </chapter>

     <chapter>
       <para>ok</para>
     </chapter>
  
     <chapter>
       <para>here</para>
       <para>there</para>
     </chapter>

</book>
The XSL File:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

  </xsl:template>

  <xsl:template match="para">
    <br>
      <xsl:value-of select="." />
    </br>
  </xsl:template>

</xsl:stylesheet>
The output (whitespaces manually modified):
<?xml version="1.0" encoding="UTF-8"?>

<h1>chapter: 1</h1><br>one  </br><br>two  </br><br>threei    </br><br>four </br>
<h1>chapter: 2</h1><br>eins </br><br>zwei </br>
<h1>chapter: 3</h1><br>apple</br>
<h1>chapter: 4</h1><br>anna </br><br>bob  </br><br>claude    </br><br>david</br><br>emilia</br>
<h1>chapter: 5</h1><br>large</br><br>small</br><br>medium    </br>
<h1>chapter: 6</h1><br>here </br><br>there</br><br>everywhere</br>
<h1>chapter: 7</h1><br>large</br><br>small</br><br>medium    </br>
<h1>chapter: 8</h1><br>what </br><br>when </br>
<h1>chapter: 9</h1><br>ok   </br>
<h1>chapter: 10</h1><br>here</br><br>there</br>