Subject:position() and last() in XQuery Author:Klarinda GW Date:17 Apr 2006 03:23 AM
Hi,
I have an XML document and I want to write an XQuery to return the position of each element and the number of elements.
My xml document is the bib.xml from W3C XML Query use cases (http://www.w3.org/TR/xquery-use-cases/) The document have 4 book elements (/bib/book). I want to write an XQuery to return all elements and adding a position and last element.
My XQuery is as follows:
<bib>
{
for $book1 in /bib/book
return
<book>
{$book1/title}
<pos>
{position()}
</pos>
<poslast>
{last()}
</poslast>
</book>
}
</bib>
But why the result of position() and last() element is not as expected? They return 1 for position() and 1 for last() for each element. But I expect them to return 1 to 4 and 4 for each element.
The result is as follows:
<bib>
<book>
<title>TCP/IP Illustrated</title>
<pos>1</pos>
<poslast>1</poslast>
</book>
<book>
<title>Advanced Programming in the Unix environment</title>
<pos>1</pos>
<poslast>1</poslast>
</book>
<book>
<title>Data on the Web</title>
<pos>1</pos>
<poslast>1</poslast>
</book>
<book>
<title>The Economics of Technology and Content for Digital TV</title>
<pos>1</pos>
<poslast>1</poslast>
</book>
</bib>
Subject:position() and last() in XQuery Author:(Deleted User) Date:17 Apr 2006 04:05 AM
Hi Klarinda,
position() returns the position of the context item inside the context sequence, while last() returns the size of the context sequence; but the FLWOR block does not change the context sequence, so the two functions will always return 1.
In order to achieve what you want you need to count the items in the sequence and then use a "positional variable":
<bib>
{
let $set := /bib/book,
$count := count($set)
for $book1 at $index in $set
return
<book>
{$book1/title}
<pos>
{$index}
</pos>
<poslast>
{$count}
</poslast>
</book>
}
</bib>