The position function in XQuery is used to determine the current position number of an
item during the iteration over a sequence.
Syntax
fn:position()
The
position
function does not require any parameters. It operates
within the context of a sequence, typically used in iterative expressions like FLWOR
loops.
Return Value
Returns the context position from the dynamic context. It returns an
integer representing the position starting with 1, not 0, of the current context
item within the context sequence.
Examples
The following table lists some sample queries and return values:
SAMPLE FUNCTION
OUTPUT
let $doc :=
<items>
<item>Apple</item>
<item>Banana</item>
<item>Cherry</item>
</items>
(: Select the last <item> :)
let $lastItem := $doc/item[position() = fn:last()]
(: Select all but the last <item> :)
let $allButLast := $doc/item[position() lt fn:last()]
return
<results>
<last-item>{$lastItem/text()}</last-item>
<all-but-last>{ $allButLast/text() }</all-but-last>
</results>