Re: [xsl] Page number ranges

Subject: Re: [xsl] Page number ranges
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Tue, 22 Jan 2002 17:02:14 +0000
Hi Gustaf,

> This works fine, but I want to add a feature so that pages 12, 13,
> 14 is written 12-14. How is that achieved?

Since the number of entries for a particular word is likely to be
fairly small, I'd probably do it as follows:

First, create a variable to hold all the word elements that you're
interested in:

  <xsl:variable name="entries" select="word[. = current()]" />

Then iterate over them as you are at the moment, in sorted order:

  <xsl:for-each select="$entries">
    <xsl:sort select="@page" data-type="number" />
    ...
  </xsl:for-each>

But within xsl:for-each, test whether there are other entries whose
page is one less than and one more than this one. If there's an entry
whose page is one less than this one, and an entry whose page is one
more than this one, then this one can be skipped over. If there's an
entry whose page is one less than this one, but not an entry whose
page is one more than this one, then you need to put the hyphen before
the page number. If there's not a page whose number is one less than
this one (and it's not the first page) then you need to give a comma
before the page number. So you get:

  <xsl:for-each select="$entries">
    <xsl:sort select="@page" data-type="number" />
    <xsl:choose>
      <xsl:when test="$entries/@page = @page - 1">
        <xsl:if test="not($entries/@page = @page + 1)">
          <xsl:value-of select="concat('-', @page)" />
        </xsl:if>
      </xsl:when>
      <xsl:otherwise>
        <xsl:if test="position() != 1">, </xsl:if>
        <xsl:value-of select="@page" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:for-each>

Note that this means that consecutive page numbers are linked with a
dash as well, so you get 12-13 rather than 12, 13. If you want them to
be separated by a comma, then you also need to test whether there's an
entry whose page is *two* less than the current page, but the general
model is the same.

If there were lots of entries, I'd be tempted to go with a solution
where you create a new result tree holding the page numbers in
ascending order, and then used the following-sibling and
preceding-sibling axes to test what the other page numbers were.
  
Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


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


Current Thread