Use generate-id() as link
File: Data.xml
<story>
<chapter>
<title>Chapter 1</title>
<para>para 1</para>
<para>item 1</para>
</chapter>
<chapter>
<title>Chapter 2</title>
<para>item 2</para>
<para>For while they sit contriving, shall the rest</para>
</chapter>
<chapter>
<title>Chapter 3</title>
<para>para 2</para>
<para>para A</para>
</chapter>
</story>
File: Transform.xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html" />
<xsl:template match="story">
<html>
<body>
<h1>Table of Contents</h1>
<xsl:apply-templates select="chapter/title" mode="toc" />
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="chapter/title">
<h2>
<a name="{generate-id()}" />
<xsl:apply-templates />
</h2>
</xsl:template>
<xsl:template match="chapter/title" mode="toc">
<p>
<a href="#{generate-id()}">
<xsl:apply-templates />
</a>
</p>
</xsl:template>
<xsl:template match="para">
<p>
<xsl:apply-templates />
</p>
</xsl:template>
<xsl:template match="story/title">
<h1>
<xsl:apply-templates />
</h1>
</xsl:template>
</xsl:stylesheet>
Output:
<html>
<body>
<h1>Table of Contents</h1>
<p><a href="#d2e5">Chapter 1</a></p>
<p><a href="#d2e17">Chapter 2</a></p>
<p><a href="#d2e29">Chapter 3</a></p>
<h2><a name="d2e5"></a>Chapter 1
</h2>
<p>para 1</p>
<p>item 1</p>
<h2><a name="d2e17"></a>Chapter 2
</h2>
<p>item 2</p>
<p>For while they sit contriving, shall the rest</p>
<h2><a name="d2e29"></a>Chapter 3
</h2>
<p>para 2</p>
<p>para A</p>
</body>
</html>
Related examples in the same category