Heston Hoffman
Heston Hoffman

Reputation: 91

Xpath query to find all elements whose attributes match those of their ancestor elements

Using this example HTML:

<body>
  <ul>
    <li><a href="one.html">One</a>
      <ul>
        <li><a href="one.html">One a</a></li> <!-- I want this one -->
        <li><a href="one.html">One b</a></li> <!-- I want this one -->
      </ul>    
      <ul>
        <li><a href="two.html">Two</a></li>
        <li><a href="three.html">Three</a></li>
        <li><a href="four.html">Four</a></li>
        <li><a href="five.html">Five</a>
          <ul>
            <li><a href="five.html">Five a</a></li> <!-- I want this one -->
            <li><a href="five.html">Five b</a></li> <!-- I want this one -->
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</body>

I need to match any <li> elements whose child <a> element contains the same <href> attribute as its parent <li>/<a>.

I've tried this, which doesn't work because it selects ALL of the elements (because it's matching the first <li> item):

//li[a[@href=ancestor::li/a/@href]]

Upvotes: 1

Views: 200

Answers (2)

Michael Kay
Michael Kay

Reputation: 163458

Try

//li[a/@href=ancestor::li[1]/a/@href]

Upvotes: 3

Hilal Arsa
Hilal Arsa

Reputation: 171

You can try these XPath :

//a[@href=//preceding-sibling::a/@href]

Here's my result on the Xpath Playground using above XML

Xpath Playground Screenshot

Upvotes: 1

Related Questions