Sriram Rammohan
Sriram Rammohan

Reputation: 91

XPath : Number of Occurrence of an element

How do i get the output for first tag starting with "<intro><longtitle" as 1 . Second tag "<intro><longtitle>" as 2 and so on using XPATH. The need is to get the occurrence of the element .

<intro><longtitle> Demo </longtitle>
..
..

<intro><longtitle> Test </longtitle>
.
.
<intro><longtitle> Demo Test</longtitle>

Regards, Sri

Upvotes: 1

Views: 924

Answers (1)

kjhughes
kjhughes

Reputation: 111726

For your XML corrected to be well-formed,

<?xml version="1.0" encoding="UTF-8"?>
<r> 
  <intro>
    <longtitle> Demo </longtitle>
  </intro>  
  <intro>
    <longtitle> Test </longtitle>
  </intro>  
  <intro>
    <longtitle> Demo Test </longtitle>
  </intro> 
</r>

you can specify the intro element with a Test string value of longtitle:

//intro[normalize-space(longtitle) = 'Test']

and count the preceding siblings,

count(//intro[normalize-space(longtitle) = 'Test']/preceding-sibling::intro) + 1

to determine that the selected intro is the second sibling:

2

Upvotes: 2

Related Questions