XPath query to select ONLY unique nodes

1.2k views Asked by At

I have what is hopefully a very simple XPath query to build that I'm stuck on (very new to XPath). I have the following xml:

 <?xml version="1.0" encoding="utf-8"?>
    <Persons>
      <Person>
        <PersonID>6352</PersonID>
        <Forename>Tristan</Forename>
      </Person>
      <Person>
        <PersonID>6353</PersonID>
        <Forename>Ruth</Forename>
      </Person>
      <Person>
        <PersonID>6913</PersonID>
        <Forename>Mina</Forename>
        <Surname>Asif</Surname>
      </Person>
      <Person>
        <PersonID>6913</PersonID>
        <Forename>Mina</Forename>
        <Surname>Asif</Surname>
      </Person>
      <Person>
        <PersonID>6914</PersonID>
        <Forename>Clark</Forename>
        <Surname>Williams</Surname>
      </Person>
    </Persons>

You can see that Person with ID 6913 is a duplicate. I the xml in an XmlDocument object and I want to use XPath in the SelectNodes method to select all Persons who have a unique PersonID. In the case above it should give me 4 out of the 5 Person items.

I also need to select all nodes below the Person item. That is PersonID, Forename, Surname (if one exists).

Any help much appreciated!

2

There are 2 answers

0
splash58 On BEST ANSWER

All Person tags that has not Person tag with the same PersonID before

//Person[not(PersonID = preceding::Person/PersonID)]

it gives you nodes Person with children. In this case 4 elements:

Element='<Person>
  <PersonID>6352</PersonID>
  <Forename>Tristan</Forename>
</Person>'
Element='<Person>
  <PersonID>6353</PersonID>
  <Forename>Ruth</Forename>
</Person>'
Element='<Person>
  <PersonID>6913</PersonID>
  <Forename>Mina</Forename>
  <Surname>Asif</Surname>
</Person>'
Element='<Person>
  <PersonID>6914</PersonID>
  <Forename>Clark</Forename>
  <Surname>Williams</Surname>
</Person>'
0
Kachna On

or

//Person[not(PersonID = following::Person/PersonID)]