[xquery-talk] position() and last()
mhk at mhk.me.uk
Wed Sep 1 10:01:46 PDT 2004
A "for" expression does not change the focus (that is, the context item,
position, or size). This is a common mistake for anyone accustomed to
xsl:for-each - I make it frequently myself.
In XQuery (but not XPath) you can assign an extra variable to represent the
current position, thus:
for $i at $pos in $items return
($i, if ($pos = count($items)) then () else ",")
Alternatively you can iterate over the positions:
(for $n in 1 to count($items)-1 return ($items[$n], ",")), $items[last()])
In many cases (but not this one) the insertion of separators between items
can be achieved using the string-join function:
position() and last() are available in XQuery but they are only really
useful inside predicates.
> -----Original Message-----
> From: talk-bounces at xquery.com
> [mailto:talk-bounces at xquery.com] On Behalf Of R. Mark Volkmann
> Sent: 01 September 2004 04:15
> To: talk at xquery.com
> Subject: [xquery-talk] position() and last()
> I know how to use these functions in XSLT, but I haven't
> figured out how to
> use them in XQuery.
> For example, suppose I want to put a comma between items, but
> not after the
> last one.
> I could do something like this.
> for $i in $items
> return (
> if (position() = last()) then () else ","
> This doesn't work. What am I doing wrong?
> talk at xquery.com
More information about the talk