Thursday 26 February 2009

Removing Duplicate Items from Xml using XPath

I needed this today, and I figured I will need it again in the future, hence my need to blog this.

I need some XPath which would remove duplicate elements from xml depending on an attribute on the item, e.g.

<Items>
<Item ItemNumber=”1/>
<Item ItemNumber=”1/>
<Item ItemNumber=”2/>
</Items>


The following XPath does the job perfectly (for my needs)



//Items/Item[not(@ItemNumber=preceding::Item/@ItemNumber)]/@ItemNumber



Which returns the following list:



<Items>
<Item ItemNumber=”1/>
<Item ItemNumber=”2/>
</Items>

No comments: