Xpath Xquery-计算具有特定属性的特定元素的数量
在标题中解释这个问题有点困难,因此下面是一个特定的xml文件示例以及代码应该返回的内容:Xpath Xquery-计算具有特定属性的特定元素的数量,xpath,xquery,Xpath,Xquery,在标题中解释这个问题有点困难,因此下面是一个特定的xml文件示例以及代码应该返回的内容: <objects> <object type='Brick' to='Up' /> <object type='Cross' to='Down' /> <object type='Brick' to='Left' /> <object type='Brick' to='Up' /> <object ty
<objects>
<object type='Brick' to='Up' />
<object type='Cross' to='Down' />
<object type='Brick' to='Left' />
<object type='Brick' to='Up' />
<object type='Circle' to='Right' />
<object type='Circle' to='Right' />
</objects>
所以我有3种对象类型:砖、圆和十字,以及3个到、上、下、左和右。我想使用xquery获得如下内容:
<objects>
<object type="Brick">
<where to="Up" count="2" />
<where to="Down" count="0" />
<where to="Left" count="1" />
<where to="Right" count="2" />
</object>
<object type="Cross">
.
.
.
</objects>
.
.
.
基本上,对于每种类型,我都希望得到right、down、left和up的子元素,以及它们在该对象类型中出现的次数。我知道,由于有限制,我可以硬编码每一个计数,并有一堆let语句,但我希望有人能提出一个更好的方法来做到这一点 如果对象类型和方向相当静态,并且有很多对象,那么最好列出已知的值,而不是使用
不同的值
,这在大序列上可能会很慢
let $object-types := ('Brick', 'Circle', 'Cross')
let $directions := ('Up', 'Down', 'Left', 'Right')
for $t in $object-types
return element object {
attribute type { $t },
for $d in $directions
let $count := count($objects/object[@type = $t][@to = $d])
return element where {
attribute to { $d },
attribute count { $count }
}
}
但如果您无法提前知道输入值,则可以动态构建这些值,如:
let $object-types := distinct-values($objects/object/@type)
...
这是一个完全动态的版本(无硬编码),
不同的值(…)
是您在XQuery 1.0中的朋友:
<objects>{
let $directions := distinct-values(//@to)
for $type in distinct-values(//object/@type)
return <object type="{$type}">{
for $to in $directions
return <where to="{$to}" count="{count(//object[@type = $type and @to = $to])}"/>
}</object>
}</objects>
{
let$directions:=不同的值(//@to)
对于不同值(//object/@type)中的$type
返回{
对于$to,在$directions中
返回
}
}
您可以使用XQuery 3对元素进行分组吗?我正在XQuery 1.0中尝试这样做