Reputation: 9945
In my XML, I have chapters with titles and I need to generate a table of contents out of it so that:
<chapter id="1"><title>Chapter 1</title><p>text</p></chapter>
<chapter id="2"><title>Chapter 2</title><p>text</p></chapter>
converts to
<!-- Table Of Contents -->
<div class="contents">
<ul>
<li><a href="#1">Chapter 1</a></li>
<li><a href="#2">Chapter 2</a></li>
</ul>
</div>
<!-- Actual Content -->
<div class="chapter" id="1"><p>text</p></div>
<div class="chapter" id="2"><p>text</p></div>
Unfortunately, when I try to use xsl:for-each
to generate the table of contents, the actual chapters seem to disappear from the output. How do I tackle this?
Upvotes: 0
Views: 1225
Reputation: 101700
This XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<div>
<div class="contents">
<ul>
<xsl:apply-templates select="chapter" mode="contents" />
</ul>
</div>
<xsl:apply-templates select="chapter" />
</div>
</xsl:template>
<xsl:template match="chapter" mode="contents">
<li>
<a href="#{@id}">
<xsl:value-of select="title" />
</a>
</li>
</xsl:template>
<xsl:template match="chapter">
<div class="chapter" id="{@id}">
<xsl:apply-templates select="*" />
</div>
</xsl:template>
<xsl:template match="chapter/title" />
</xsl:stylesheet>
when applied to this input:
<chapters>
<chapter id="1">
<title>Chapter 1</title>
<p>text</p>
</chapter>
<chapter id="2">
<title>Chapter 2</title>
<p>text</p>
</chapter>
</chapters>
will produce:
<div>
<div class="contents">
<ul>
<li>
<a href="#1">Chapter 1</a>
</li>
<li>
<a href="#2">Chapter 2</a>
</li>
</ul>
</div>
<div class="chapter" id="1">
<p>text</p>
</div>
<div class="chapter" id="2">
<p>text</p>
</div>
</div>
If you could show us your XSLT (I would think that with 2,410 reputation points providing that would be obvious to you), we can tell you what you're doing incorrectly.
Upvotes: 6