Monday, April 8, 2013

Use preceding-sibling to find all unique elements

Recently I need to write a xpath expression to find all unique elements from one XML message.  The below is the simplified XML document that demonstrate the problem to be solved.  Here I want to get a list of all unique of all a elements.  The of values in the result list should be 123, 120, 129,345 and 340.

<?xml version="1.0" encoding="UTF-8"?>

<!--Sample XML file generated by XMLSpy v2008 sp1 (http://www.altova.com)-->

<db:p>

 <db:ss>

  <db:tt>

   <db:a>123</db:a>

   <db:a>120</db:a>

  </db:tt>

  <db:tt>

   <db:a>123</db:a>

   <db:a>129</db:a>

  </db:tt>

 </db:ss>

 <db:ss>

  <db:tt>

   <db:a>345</db:a>

   <db:a>120</db:a>

   <db:a>123</db:a>

   <db:a>340</db:a>

  </db:tt>

 </db:ss>

</db:p>


After some tries I come out with the following xpath expression.

/*:p/*:ss/*:tt/*:a[ not(. = ../preceding-sibling::*/*:a)  and not(. =  ../../preceding-sibling::*/*:tt/*:a)]

Here I use two preceding-sibling because <a> element is under <ss> and <tt> elements.

No comments:

Post a Comment