<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:output method="xml"/>
  <xsl:strip-space elements="*"/>
  
  <xsl:template match="/html/body" priority="1">
    <toc>
      <xsl:apply-templates select="ol"/>
      <xsl:apply-templates select="ul"/>
    </toc>
  </xsl:template>
  
  <xsl:template match="text()" priority="1"/>
  
  <xsl:template name="xpath">
    <xsl:param name="ancestors" select="ancestor-or-self::*"/>
    <xsl:text>#element(</xsl:text>
    <xsl:for-each select="$ancestors">
      <xsl:variable name="myname" select="name()"/>
      <xsl:text>/</xsl:text>
      <xsl:value-of select="count(preceding-sibling::*) + 1"/>
    </xsl:for-each>
    <xsl:text>)</xsl:text>
  </xsl:template>
  
  <xsl:attribute-set name="targetattr">
    <xsl:attribute namespace="http://www.w3.org/1999/xlink" name="xlink:href">
      <xsl:call-template name="xpath"/>
    </xsl:attribute>
  </xsl:attribute-set>
  
  <xsl:template match="li" priority="3">
    <tocitem>
      <link xsl:use-attribute-sets="targetattr">
	<title><xsl:value-of select="normalize-space(descendant-or-self::text())"/></title>
      </link>
      <xsl:apply-templates/>
    </tocitem>
  </xsl:template>
</xsl:stylesheet>
