Alex Rivera | Logout

Updating counter in XQuery

Asked 2012-04-24T08:53:03.747
13

I want to create a counter in xquery. My initial attempt looked like the following:

let $count := 0
for $prod in $collection
let $count := $count + 1
return 
<counter>{$count }</counter>

Expected result:

<counter>1</counter>
<counter>2</counter>  
<counter>3</counter>

Actual result:

<counter>1</counter>
<counter>1</counter>  
<counter>1</counter>

The $count variable either failing to update or being reset. Why can't I reassign an existing variable? What would be a better way to get the desired result?

Edit
Report

3 Answers

23

Try using 'at':

for $d at $p in $collection
return 
element counter { $p }

This will give you the position of each '$d'. If you want to use this together with the order by clause, this won't work since the position is based on the initial order, not on the sort result. To overcome this, just save the sorted result of the FLWOR expression in a variable, and use the at clause in a second FLWOR that just iterates over the first, sorted result.

let $sortResult := for $item in $collection
                   order by $item/id
                   return $item

for $sortItem at $position in $sortResult
return <item position="{$position}"> ... </item>
answered 2012-04-24T09:29:27.567
9

As @Ranon said, all XQuery values are immutable, so you can't update a variable. But if you you really need an updateable number (shouldn't be too often), you can use recursion:

declare function local:loop($seq, $count) {
  if(empty($seq)) then ()
  else
    let $prod  := $seq[1],
        $count := $count + 1
    return (
      <count>{ $count }</count>,
      local:loop($seq[position() > 1], $count)
    )
};

local:loop($collection, 0)

This behaves exactly as you intended with your example.

In XQuery 3.0 a more general version of this function is even defined in the standard library: fn:fold-right($f, $zero, $seq)

That said, in your example you should definitely use at $count as shown by @tohuwawohu.

answered 2012-04-24T10:01:27.283
2

I think you are looking for something like:

XQUERY:

for $x in (1 to 10)
return
  <counter>{$x}</counter>

OUTPUT:

<counter>1</counter>
<counter>2</counter>
<counter>3</counter>
<counter>4</counter>
<counter>5</counter>
<counter>6</counter>
<counter>7</counter>
<counter>8</counter>
<counter>9</counter>
<counter>10</counter>
answered 2013-04-18T04:43:05.470

Your Answer