Jenananthan
Jenananthan

Reputation: 1401

Select distinct elements in xpath

I have following xml

<?xml version="1.0" encoding="UTF-8"?>
<results>
   <result>
      <status>A</status>
   </result>
   <result>
      <status>A</status>
   </result>
   <result>
      <status>B</status>
   </result>
</results>

And I want to get the result elements based on the distinct value of child element status . i.e in above case only one result element should be return which contains A

   <result>
      <status>A</status>
   </result>
   <result>
      <status>B</status>
   </result>

Appreciate your help on this to get a working xpath expression.

Upvotes: 0

Views: 2550

Answers (2)

Andersson
Andersson

Reputation: 52665

You can use this one to get required output:

/results/result[not(status=preceding-sibling::result/status)]

It should return result node in case there were no preceding result node with the same status value (distinct result nodes)

Upvotes: 1

zx485
zx485

Reputation: 29022

In XPath-2.0 you can use the distinct-values(...) function with a for-loop like this:

for $d in distinct-values(/results/result/status) return /results/result[status=$d][1]

Upvotes: 1

Related Questions