Hunting for Dinosaurs with <xsl:for-each> - Page 11
November 4, 2002
The first few lines of contents_2.xsl
are the same as in our previous example – defining the version and namespace,
making sure IE 5 and IE 5.5 perform transformations, defining the Identity
Transformation, finding the <body> tag, and inserting the header
links. We then add some more content to the header, using the following section
of the stylesheet:
<h2>Quick reference</h2>
<ul>
<xsl:for-each
select="h2">
<li>
<a>
<xsl:attribute
name="href">
#<xsl:value-of
select="text()"/>
</xsl:attribute>
<xsl:value-of
select="text()"/>
</a>
</li>
</xsl:for-each>
</ul>
The first two lines of this section give a header and begin the list for
our TOC, and the last line closes it. The interesting bit comes in the middle.
Here, we set up a loop to find all <h2> tags in the <body> element content, and create a
list of anchor links based on the contents of these <h2> tags. Because all
of our dinosaur names in the page are nicely wrapped in <h2> elements (for example, <h2>Tyrannosaurus Rex</h2>), this
becomes a list of links to our dinosaurs.
For each <h2> in the body
of the page, we first output an <li>
tag. We then create an <a>
tag, use xsl:attribute
to add an attribute called 'href',
and set this attribute to be a hash symbol followed by the content of the
<h2> tag. We then close the href attribute. We use the text content of
the <h2> tag again to output
the dinosaur name as visible text for the link, and finish off with an </a> tag to close the link. Finally,
we close our <li> element,
and end the for-each loop with </xsl:for-each>,
giving (for example):
<li><a href="#Tyrannosaurus Rex">Tyrannosaurus
Rex</a></li>
For dinosaur_2.xml,
the complete block of navigation created by this code looks like this:
<h2>Quick reference</h2>
<ul>
<li><a
href="#Brontosaurus">Brontosaurus</a></li>
<li><a
href="#Tyrannosaurus Rex">Tyrannosaurus Rex</a></li>
<li><a
href="#Stegosaurus">Stegosaurus</a></li>
</ul>
Let's add a pterodactyl to dinosaur_2.xml:
<h2>Pterodactyl</h2>
A Pterodactyl can fly round at high speeds.
<ul>
<li><b>Weight:</b>
0.05 tons</li>
<li><b>Length:</b>
2 m</li>
<li><b>Color:</b>
Gray</li>
</ul>
Example 2: Creating a Table of Contents with XSLT - Page 10
Practical XML for the Web
Hunting for Dinosaurs with <xsl:for-each>(Cont.) - Page 12
|