XQuery counters inside a for

jong picture jong · Apr 13, 2011 · Viewed 15.5k times · Source

Let's say I have the XQuery code below:

   for $y in doc("file.xml")/A/B

        for $x in $y/C where $x/constraint1 != "-" and $x/constraint2 > 2.00
            do stuff 

Can I use a counter, to count how many my code will enter inside the second for loop? I tried this:

   for $y in doc("file.xml")/A/B
       let $i := 0
        for $x in $y/C where $x/constraint1 != "-" and $x/constraint2 > 2.00
            $i := $i + 1

but I got compile errors. I also I need to sum some constraints like this:

   for $y in doc("file.xml")/A/B
       let $i := 0
       let $sum := 0
        for $x in $y/C where $x/constraint1 != "-" and $x/constraint2 > 2.13
            $i := $i + 1
            $sum := $sum + $x/constraint2

but of course this didn't work either :(.

Any suggestions will be highly appreciated. Also, can you suggest a good book/tutorial/site for doing such stuff?

Answer

Michael Kay picture Michael Kay · Apr 13, 2011

You don't need it very often, but if you really do need a counter variable inside an XQuery for expression (analogous to position() in an xsl:for-each) you can use an at variable

for $x at $pos in //item return
  <item position="{$pos}" value="{string($x)}"/>