1

我对 xquery 很陌生,我正在尝试使用 xquery 检查属性是否存在于元素中,如果存在则返回,仅返回具有 id 的 b 元素。

我尝试了以下方法:

输入

<a>
 <b id="id2">text</b>
 <x id="id4">text</x>
 <b>text</b>
 <b id="id5">text</b>
</a>

查询:

for $x in (*:a/*:b)
let $new:=
let $id := exists($x/@id)
let $c := if ($id = true()) then ($x/@id/string()) else()
return
<string key="id">{$c}</string>
return ($new)

但我也得到了不存在项目的返回字符串。如何不返回没有 id 的元素。

输出:

 <string key="id">id2</string>
 <string key="id"/>
 <string key="id">id5</string>

有什么简单的方法可以做到这一点。

4

1 回答 1

3

这是一个紧凑的解决方案:

a/b/@id/<string key="id">{ string(.) }</string>

这是一个更详细的替代方案(还有很多其他的):

for $b in *:a/*:b
let $new := 
  let $id := $b/@id/string()
  where exists($id)
  return <string key="id">{ $id }</string>
return $new
于 2018-02-26T08:32:18.170 回答