fn:sum 错误 "cannot cast to xs:double"

fn:sum error "cannot cast to xs:double"

我正在尝试添加多个节点(名称和节点数量不确定)。

执行查询

for $x in //onboard/*
return $x

return这个(以及更多)

<total>
    <one/>
</total>
<total>
  <one>124</one>
  <two>1</two>
  <three>0</three>
</total>
<total>
  <one>46</one>
</total>
<total>
  <one>129</one>
  <two>1</two>
  <three>0</three>
</total>
<seafarers>
  <one>149</one>
  <two>3</two>
  <three>3</three>
  <six>155</six>
</seafarers>
<soldiers>
  <one>135</one>
  <six>118</six>
</soldiers>

per child 其名称为 'total' 或 'seafarers' 或类似但未固定的东西我想 return 所有节点值的总和从节点 'one' 到节点 'six' 同样,不确定有多少个节点以及它们是否存在(每个节点至少存在 1 个数字节点,但这不一定是 'one')。

到目前为止,我尝试过的所有方法都会导致类型转换错误或不正确的答案。

对于提供的示例代码,所需的答案是:

125
46
130
310
253

你可以这样试试:

for $x in //onboard/*[*]
return sum($x/*)

内容如下:对于 $x,因为 <onboard> 中的每个 child 至少有一个 child 元素,return 所有 child 的总和$x.

的 ]ren 元素

更新:

原来问题是由于传递给 sum() 函数的空元素所致。这是避免错误的另一种可能方法:

for $x in //onboard/*[normalize-space()]
return sum($x/*[normalize-space()])

以上xquery只考虑children of <onboard>non-empty元素。然后在sum()操作中,再次只考虑$x的非空child。