Select Nth child Node in HTML Document

c# html html-agility-pack xpath

Question

I have an html document that I need to grab all table elements that are the 5th table deep in the DOM, not to be confused with the 5th child table. My problem is this 5 table deep structure could be wrapped in any number of div elements so I can't use an absolute path such as

/html/body/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table

For example:

<body>    
    <table>    
        <table>
            <table>
                <table>
                   <!--Grab this one -->
                   <table>
                   </table>
                </table>
            </table>
       </table>
    </table>
</body>

Or This:

 <body> 
    <div> <!--Could be wrapped more than just once though -->  
        <table>    
            <table>
                <table>
                    <table>
                       <!--Grab this one -->
                       <table>
                       </table>
                    </table>
                </table>
           </table>
        </table>
    </div>
</body>

Accepted Answer

Use:

(//table[count(ancestor::table) = 4])[1]

This selects the first table in the document that has exactly four ancestors named table .


Popular Answer

I believe you'd want the // expression between each element, making the full expression:

//table//table//table//table//table

This will select any table that has 4 tables anywhere in its path




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why