Re: [xsl] simulating for with foreach

Subject: Re: [xsl] simulating for with foreach
From: David Carlisle <davidc@xxxxxxxxx>
Date: Wed, 5 Jul 2006 13:11:43 +0100
  Thank you very much. That fully solved my problem, but just for my
  curiosity, why position() (and also last()) do return sequential
  numbers instead of real positions. I mean position() returns 1, 2, 3
  instead of 1, 4, 9...


position() has no relation to the position of the node in the input
document, it is the position of the node in the current node list (ie
the nodes just selected). Similarly last() is defined to be the length
of the current node list. The same node will have different position()
depending on how it is selected

If you go
<xsl:for-each select=".">
 ..

then position()=last()=1 whetever node is selected as . selects a list
of length one and the current node is the first (and only) item of that
list.

In many (most) cases the sequential node ordering in the input document
is fairly irrelevant and it's position() that you want.

Given

<x>
 <! an example -->
 <a/>
 <b/>
  <!-- <c/> -->
 <d/>
</x>

then if you say select="*" you get a b and c with positions 1,2,3 which
you may use to number the output or whatever.

Child nodes of x thoughhave fairly arbitrary positions affected by
indentation and comments,  if you select="node() you will see whet you
call "real position" 
 1 (white space text)
 2 comment
 3 (white space text)
 4 <a/>
 5 (white space text)
 6 <b/>
 7 (white space text)
 8 comment
 9 (white space text)
 8 <d/>
10 (white space text)

so the three elements you are really interested in have positions 4,6
and 8.


David

Current Thread