在XQuery中更新计数器 [英] Updating counter in XQuery

查看:98
本文介绍了在XQuery中更新计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在xquery中创建一个计数器.我最初的尝试如下所示:

I want to create a counter in xquery. My initial attempt looked like the following:

let $count := 0
for $prod in $collection
let $count := $count + 1
return 
<counter>{$count }</counter>

预期结果:

<counter>1</counter>
<counter>2</counter>  
<counter>3</counter>

实际结果:

<counter>1</counter>
<counter>1</counter>  
<counter>1</counter>

$count变量无法更新或被重置.为什么不能重新分配现有变量?什么是获得预期结果的更好方法?

The $count variable either failing to update or being reset. Why can't I reassign an existing variable? What would be a better way to get the desired result?

推荐答案

尝试使用'at':

for $d at $p in $collection
return 
element counter { $p }

这将为您提供每个"$ d"的位置.如果要将其与order by子句一起使用,则此方法将不起作用,因为位置基于初始顺序,而不是基于排序结果.为了克服这个问题,只需将FLWOR表达式的排序结果保存在一个变量中,然后在第二个FLWOR中使用at子句,该子句仅遍历第一个排序结果即可.

This will give you the position of each '$d'. If you want to use this together with the order by clause, this won't work since the position is based on the initial order, not on the sort result. To overcome this, just save the sorted result of the FLWOR expression in a variable, and use the at clause in a second FLWOR that just iterates over the first, sorted result.

let $sortResult := for $item in $collection
                   order by $item/id
                   return $item

for $sortItem at $position in $sortResult
return <item position="{$position}"> ... </item>

这篇关于在XQuery中更新计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆