Search code examples
xmlxsltxqueryexist-db

xquery skip elements if they exist already


$a is

(<pet name="a1">
<age num="1"/>
</pet>,
<pet name="a2">
<age num="2"/>
</pet>)

$b is

(<pet name="a2">
<age num="9"/>
</pet>,
<pet name="a3">
<age num="11"/>
</pet>
<pet name="a3">
<age num="14"/>
</pet>

)

I am trying to get the following as output (Everything in $a and everything in $b except those already printed out) i.e,

(<pet name="a1">
<age num="1"/>
</pet>,
<pet name="a2">
<age num="2"/>
</pet>,
<pet name="a3">
<age num="11"/>
<age num="14"/>
</pet>)

Since <pet name="a2"> is already printed from $a, the same element with same attribute in $b must be skipped, I tried the below code in xquery, but I am unable to get the required result.

for $l in $a
    for $m in $b
      return if ($m/@name!=$l/@name)

Solution

  • This can be solved more simply without loops by joining the sequences and filtering the second using a predicate expression:

    ($a | $b[not(@name = $a/@name)])