for 内的 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
我可以使用计数器来计算有多少代码将进入第二个 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
但出现编译错误。我还需要总结一些这样的约束:
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
但是当然这也不起作用:(。
任何建议将不胜感激。 另外,你能推荐一本好书/教程/网站来做这些事情吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您还没有理解声明性范式的基础知识。
总计数和总和将为:
部分计数和总和将为:
I don't think you have understood the basics of declarative paradigm.
Total count and sum would be:
Partial count and sum would be:
要在循环中显示计数器,最好、更简单的方法是在 for 循环中添加 at $pos 。 $pos 将用作计数器。
代码片段:
输出:
To Display counter in loop the best and easier way is to add at $pos in your for loop. $pos will work as a counter.
Code Snippet :
Output:
如果您不想对集合中的每个项目进行计数或操作,但只想在特定条件适用时进行计数/操作,则这是另一种解决方案。
在这种情况下,您可能会记得 XQuery 的函数式编程范例,并通过使用递归函数调用来实现此计数/操作:
更简单的方法是使用适当的 XPath 表达式:
或者甚至
递归解决方案可能会非常有帮助,如果您想要用 XQuery 实现更复杂的东西...
Here is another solution, if you don't want to count or act on every item of a collection, but you want to count/act only, if a certain condition applies.
In that case you might remember the functional programming paradigm of XQuery and implement this counting/acting by using recursive function calls:
The more easier way would be the usage of an appropriate XPath expression:
or even
The recursive solution might be quite helpful, if you want to implement something more complex with XQuery...
您并不经常需要它,但如果您确实需要在 XQuery
for
表达式中使用计数器变量(类似于xsl 中的
),您可以使用position()
): for-eachat
变量You don't need it very often, but if you really do need a counter variable inside an XQuery
for
expression (analogous toposition()
in anxsl:for-each
) you can use anat
variable