Re: [xsl] numbering and sorting compatibility issue

Subject: Re: [xsl] numbering and sorting compatibility issue
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Sat, 22 Mar 2003 12:34:17 +0000
Hi Andrew,

> How I can change priority for <xsl:number/> for correct
> numbering+sorting? By default first xsl processor does numbering and
> after that sorting.

<xsl:number> *always* gives you a number that's based on the position
of the node in the source tree. To get a number that's based on the
order in which the nodes are processed, you should use the position()
function.

> It's so confusing for "multilevel" numbering as for xml:
> <Lev1>
>     <Lev2>
>         <Lev3 x="y"/>
>     </Lev2>
>     <Lev2>
>         <Lev3 x="z"/>
>     </Lev2>
>     ...
> </Lev1>
> xsl:
> <template select="Lev1">
>     <apply-templates/>
> </template>
> <template select="Lev2">
>     <apply-templates>
>         <sort select="@x"/>
>     </apply-templates>
> </template>
> <template select="Lev3">
>     <tr>
>         <td><xsl:number level="any"/></td>
>         <td>...</td>
>     </tr>
> </template>
<
> so I want to number "Lev3" through all document and sort "Lev3" on
> "Lev2" by "x". How I can acomplish this?

I's a bit hard to tell what you're aiming for without seeing the
output that you want. In particular, the XSLT code that you're using
is applying templates to the <Lev3> elements within a particular
<Lev2> in order of their x attribute, but in your example XML there's
only one <Lev3> element within each <Lev2> element, so the sort
wouldn't have any effect.

I suspect that you want to apply templates to all the <Lev3> elements
(across the document, sorted in order of their x attribute. In which
case, I'd use:

<xsl:template match="Lev1">
  <xsl:for-each select="Lev2/Lev3">
    <xsl:sort select="@x" />
    <tr>
      <td><xsl:value-of select="position()" /></td>
      <td>...</td>
    </tr>
  </xsl:for-each>
</xsl:template>

(I generally use <xsl:for-each> rather than <xsl:apply-templates> when
the position() function is used, because the output is effected by
exactly which nodes are selected and what order they're processed, so
it's useful to keep the two together.)

If you really have several <Lev3> elements within each <Lev2> element,
and you only want the sort to effect the <Lev3> elements within the
same <Lev2> elements, then numbering is more complicated: you have to
add the position() (in sorted order) to the number of <Lev3> elements
within the <Lev2> elements that precede this <Lev3> element's parent
<Lev2> element. The XPath would be:

  position() + count(../preceding-sibling::Lev2/Lev3)

Cheers,

Jeni

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


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


Current Thread