xsl-list
[Top] [All Lists]

Re: preceding-sibling after sort gives unexpected result

2003-09-11 10:45:38
Kaine Varley wrote:
I am trying to process a document similar to the one below, using the
stylesheet below. My problem is that after I have performed the sort, I
appear to get the preceding sibling in the original document order rather
than in the newly sorted order.

That's exactly how the preceding-sibling axis is supposed to
work. If you want to reference the preceding node in the sorted
sequence, you have several options:
- Use a two stage approach, by copying the sorted nodes into
  a variable. You'll need a node-set() extension function to
  further fork on the data:
  <xsl:variable name="sorted-stuff">
    <sorted-stuff>
      <xsl:for-each select="$stuff-to-be-sorted">
        <xsl:sort select="my-sort-key"/>
        <xsl:copy-of select="."/>
     </xsl:for-each>
   </sorted-stuff>
  </xsl:variable>
  <xsl:for-each select="xx:node-set($sorted-stuff)/sorted-stuff">
    ...
  Use with caution if your data set is very large.

- Access the previous element by index. You'll need to sort the
  selected stuff again. This is a sort of brute force approach,
  use with caution in all cases:
  <xsl:for-each select="$stuff-to-be-sorted">
    <xsl:variable mname="this-index" select="position()"/>
    <xsl:text>Previous: </xsl:text>
    <xsl:for-each select="$stuff-to-be-sorted">
      <if test="position()=$this-index - 1">
        <xsl:value-of select="."/>
      </xsl:if>
    </xsl:for-each>
  </xsl:for-each>

- Do some analysis whether you can determine the previous node
  in the sorted sequence by some other method.

- Use an XSLT 2.0 processor. Check the spec for details, specifically
  the sort() XPath 2.0 function.

J.Pietschmann


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