XQuery计数器里面的for

jon*_*ong 5 xml counter xquery

假设我有以下XQuery代码:

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

        for $x in $y/C where $x/constraint1 != "-" and $x/constraint2 > 2.00
            do stuff 
Run Code Online (Sandbox Code Playgroud)

我可以使用计数器来计算我的代码在第二个for循环中输入的数量吗?我试过这个:

   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
Run Code Online (Sandbox Code Playgroud)

但是我遇到了编译错误.我还需要总结一些这样的约束:

   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
Run Code Online (Sandbox Code Playgroud)

但当然这也不起作用:(.

任何建议将受到高度赞赏.另外,你能建议一本好的书/教程/网站来做这些事吗?

Mic*_*Kay 18

你不经常需要它,但是如果你确实需要在XQuery for expression中使用一个计数器变量(类似于xsl:for-each中的position())你可以在"at"变量使用它

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


小智 1

我认为您还没有理解声明性范式的基础知识。

总数和总和将为:

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

部分计数和总和将为:

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))
Run Code Online (Sandbox Code Playgroud)