Maybe I’m doing something terribly wrong, but I can’t get position() to work. In the following query, the function always delivers “1”, even if $a contains multiple “track” child elements. BTW, position() does work in a filter expression such as $a/track[position()=2], but it fails when used in the body of a FOR loop.
The for loop iterates through each track, and assigns the value to a variable ($t). Therefore the variable will contain only one track at a time, and therefore, its position will always be 1.
Perhaps a workaround could be:
LET $numTracks = count($a/track) FOR $t IN (1 TO $numTracks) LET $track = $a/track[$t] RETURN
Obviously, to FOR loop seems to create a new context consisting only of the track element selected for one iteration. Not very intuitive though, one should rather expect the whole album/track node list as the context. The Working Draft, hoever, is not very specific about context in loops.
I’m afraid this one is going to catch a lot of people out: the dynamic context (context item, position, and size) are not changed within a FLWR expression. If you want to use the position, you have to turn it around as:
for $i in 1 to count($sequence) let $x := $sequence[$i]