Creating table of contents of XHTML document during XSL transformation is surprisingly difficult task and therefore it is often done improperly. There is a very good analysis of this problem, but the proposed solution has many disadvantages, so I tried to figure out a better algorithm, which would be generaly more suitable for pure functional programming languages like XSL.

Disadvantages of existing solution

There is a fairly complex solution of TOC for XHTML in the article mentioned above, but it has following disadvantages:

Because of those drawbacks I decided to investigate the possibility of an alternative, more recursive-based, algorithm.

My solution

There are two subproblems in creating a TOC: Creating an anchor ids and creating the table itself.

Chapter numbering

Since properly generated chapter number (e.g. 4.2.5.) is unique in the document, I decided to use it as anchor ids (in the same way as in the mentioned article). My design of recursive algorithm for this is as follows:





Some notes:

TOC generation

TOC generation itself builds over the same principles as chapter numbering - recursion and heading levels.


  • ]]>

    For printing a complete TOC this template has to be applied on all top level headings, for example like this:


    Some notes:


    I created XSL templates for constructing table of contents out of headings in XHTML document which doesn't suffer from drawbacks identified in existing solution. Although simplicity of templates comes for the price of insanely complicated xpath expressions I would prefer this solution even for XSLT 2.0 environments for it's flexibility.

    Last update