Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XQuery counters inside a for

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?

like image 346
jong Avatar asked Apr 13 '11 16:04

jong


1 Answers

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)}"/>
like image 123
Michael Kay Avatar answered Oct 16 '22 01:10

Michael Kay