1

I am very new to xquery, I am trying to check if the attribute exists in the element using xquery, if exists return, return only for the b element which has id.

I tried the following:

Input

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

XQuery:

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)

But I am getting the return string for the not existence item as well. How to not return for the elements which don't have id.

output:

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

Is there any easy method to do this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
VSe
  • 919
  • 2
  • 13
  • 29

1 Answers1

3

This is a compact solution:

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

Here is a more verbose alternative (there are many others):

for $b in *:a/*:b
let $new := 
  let $id := $b/@id/string()
  where exists($id)
  return <string key="id">{ $id }</string>
return $new
Christian Grün
  • 6,012
  • 18
  • 34