[xsl] Interesting numbering problem

Subject: [xsl] Interesting numbering problem
From: Joerg Pietschmann <joerg.pietschmann@xxxxxx>
Date: Wed, 11 Apr 2001 14:35:55 +0200
Hello all,
here is an interesting problem that my students presented me.

Take this simple FAQ XML file:

    <q>Sample question.</q>
    <a>Sample answer.</a>
    <q>A <keyword>hairy</keyword> question.</q>
    <a>Another answer.</a>

This should be transformed into text, with a keyword index.
The question should be numbered, both in normal text and in
the keyword index, and the questions should be sorted
(alphabetically, just to have a simple example):

Q1: A hairy question.
A: Another answer.

Q2: Sample question.
A: Sample answer.
hairy: question 1

It took me a while to find a XSL which generates this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  <xsl:output method="text" encoding="ASCII"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="faq">
    <xsl:apply-templates><xsl:sort select="q"/></xsl:apply-templates>
    <xsl:apply-templates select="//keyword" mode="keywordindex"/>

  <xsl:template match="qa">
    <xsl:value-of select="position()"/>
    <xsl:text>: </xsl:text>
    <xsl:apply-templates select="q"/>
A: </xsl:text>
    <xsl:apply-templates select="a"/>

  <xsl:template match="keyword" mode="keywordindex">
    <xsl:value-of select="."/>
    <xsl:text>: question </xsl:text>
    <xsl:variable name="q" select="generate-id(ancestor::qa)"/>
    <xsl:for-each select="//qa">
      <xsl:sort select="q"/>
      <xsl:if test="generate-id()=$q">
        <xsl:value-of select="position()"/>

The method for generating the question number in the keyword index appears
to be somewhat complicated and is a potential performance drain. Is there
something easier? The sorting defeats using 1+count(ancestor::qa/preceding::qa)
for the question number in the keyword index generation template (or am i
(i have the feeling i'll get the recommendation to build a variable with
the sorted qa-elements and work on that, using node-set() :-)


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list

Current Thread