0

I have the following XML data for which I would like create an xpath statement which i think might contain nested count()

Here is the XML data for 5 CD Rentals

<?xml version="1.0"?> 

<DataBase>
  <!-- CD Rental 1 -->
  <Rental>
      <cd>
        <title>title1</title>
      </cd>
      <person uniqueID = "1">
        <name>name1</name>
      </person>
  </Rental>

  <!-- CD Rental 2 -->
  <Rental>
    <cd>
      <title>title2</title>
    </cd>
    <person uniqueID = "2">
      <name>name2</name>
    </person>
  </Rental>

  <!-- CD Rental 3 -->
  <Rental>
    <cd>
      <title>title3</title>
    </cd>
    <person uniqueID = "1">
      <name>name1</name>
    </person>
  </Rental>

  <!-- CD Rental 4 -->
  <Rental>
    <cd>
      <title>title4</title>
    </cd>
    <person uniqueID = "3">
      <name>name3</name>
    </person>
  </Rental>

  <!-- CD Rental 5 -->
  <Rental>
    <cd>
      <title>title5</title>
    </cd>
    <person uniqueID = "2">
      <name>name2</name>
    </person>
  </Rental>
  
</DataBase>

The xpath I had in mind was

Count the number of persons who rented multiple CD's

In the above XML data, the person with name as name1 and the person with name as name2 rented 2 CD's while name3 only rented 1 CD. So the answer I am expecting is 2. What could be a possible xpath for this?

Criss Hills
  • 189
  • 1
  • 12

1 Answers1

1

One possible XPath expression would be:

count(//name[.=preceding::name][not(. = following::name)])

xpathtester demo

Brief explanation about the expression inside count():

  • //name[.=preceding::name]: find all elements name which have preceding element name with the same value, in other words name with duplicate
  • [not(. = following::name)]: further filter name elements found by the previous piece of XPath to return only the last of each duplicated name (distinct in Xpath?)
har07
  • 88,338
  • 12
  • 84
  • 137
  • hey, that absolutely works and tysm! but the syntax and logic are quite complex, do u mind editing your answer to have a much simpler xpath? – Criss Hills Mar 11 '21 at 12:49
  • XPath 1.0 only provide limited functionalities, so that's the simplest I can think of – har07 Mar 11 '21 at 13:40