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 calculate how much my code will be entered in the second 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 compilation errors. I also need to summarize some limitations 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 it didn't work either: (.

Any suggestions would be highly appreciated. Also, can you offer a good book / textbook / website for creating such materials?

+5
source share
4 answers

You don't need this very often, but if you really need a counter variable inside an XQuery expression for(similar to position()c xsl:for-each), you can use the variableat

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

, .

:

let $items := doc('file.xml')/A/B/C[constraint1 != '-' and constraint2 > 2.13]
return ('Count:', count($items), 'Sum:', sum($items/constraint2))

:

let $items := doc('file.xml')/A/B/C[constraint1 != '-' and constraint2 > 2.13]
for $pos in (1 to count($items))
return ('Count:', $pos, 'Sum:', sum($items[position() le $pos]/constraint2))
+1

, $pos for. $pos .

:

{for $artist **at $pos** in (/ns:Entertainment/ns:Artists/ns:Name)

  return
      <tr><td>{$pos}&nbsp;&nbsp;
    {$artist}</td></tr>

}

:

1   Artist

2   Artist 

3   Artist 

4   Artist

5   Artist

6   Artist
0

, , /, . XQuery / :

declare function ActIf($collection as element(*)*, $index as xs:integer, $indexMax as xs:integer, $condition as xs:string, $count as xs:integer) as xs:integer
{
if($index <= $indexMax) then
    let $element := $collection[$index]
    if($element/xyz/text() eq $condition) then
        (: here you can call a user-defined function before continuing to the next element :)
        ActIf($collection, $index + 1, $indexMax, $condition, $count + 1)
    else
        ActIf($collection, $index + 1, $indexMax, $condition, $count)
else (: no more items left:)
    $count
};

XPath:

for $element at $count in $collection[xyz = $condition]
return
    (: call your user-defined function :)

myFunction($collection[xyz = $condition])

A recursive solution can be quite useful if you want to implement something more complex with XQuery ...

0
source

All Articles