bjo
bjo

Reputation: 550

Excluding elements in XQuery

I have an XML element such as:

<items>
   <item>
      <size>360</size>
      <quantity>400</quantity>
   <item>
   <item>
      <size>540</size>
      <quantity>1200</quantity>
   <item>
   <item>
      <size>360</size>
      <quantity>600</quantity>
   <item>
   <item>
      <size>800</size>
      <quantity>750</quantity>
   <item>
</items>

What I need to do is iterate over this element and pull out ONLY the first item elements with a distinct size element. So I want to have:

<item>
  <size>360</size>
  <quantity>400</quantity>
<item>
<item>
   <size>540</size>
   <quantity>1200</quantity>
<item>
<item>
   <size>800</size>
   <quantity>750</quantity>
<item>

Removing the second item element with a size of 360. Is there a way of filtering these out in a for loop filter statement?

Upvotes: 3

Views: 371

Answers (2)

Oliver Hallam
Oliver Hallam

Reputation: 4262

One way is:

for $item in $items
where $item is $items[size = $item/size][1]
return $item

another is

let $sizes = distinct-values($items/size)
for $size in $sizes
return $items[size = $size][1]

and yet another (more evil) way is

$items[index-of($items/size, size)[1]]

Upvotes: 3

wcandillon
wcandillon

Reputation: 2176

Is the following query helping?

for $item in $items
let $size := number($item/size/text()) 
return
  if($size != 360) then
    $item
  else ()

Upvotes: -1

Related Questions