Dhinesh
Dhinesh

Reputation: 139

What is the difference between child and descendant XPath axes?

<div class='ABC'>
    <a href='url.com'></a>
    <div class='XXX'></a>
    <div id='EDF'>
        <a href='url.com'></a>
    </div>  
    <div class='XYZ'></div>
</div>

As per my understanding //div[@class='ABC'//child::*] should yield search result of 4 and //div[@class='ABC'//descendant::*] should yield 5. But, in reality, both are yielding search result of 5.

Can anyone help me understand the difference?

Upvotes: 2

Views: 500

Answers (2)

kjhughes
kjhughes

Reputation: 111531

First of all, fix your markup to be well-formed (<div> cannot be closed with a </a>):

<div class='ABC'>
    <a href='url.com'></a>
    <div class='XXX'></div>
    <div id='EDF'>
        <a href='url.com'></a>
    </div>  
    <div class='XYZ'></div>
</div>

Then, fix your XPath syntax:

  1. count(//div[@class='ABC']/child::*) returns 4.
  2. count(//div[@class='ABC']/descendant::*) returns 5.

Which should align with your expectation that the XPath child axis selects immediate children only while the XPath descendant axis selects children and children's children recursively.

Upvotes: 3

Marcel
Marcel

Reputation: 1463

I believe your syntax is wrong, using the following XPath's I get 2 children and 5 descendants

//div[@class='ABC']/child::*
//div[@class='ABC']/descendant::*

Upvotes: 0

Related Questions