chhenning chhenning - 28 days ago 5
C# Question

When to use double slash in HtmlAgilityPack SelectNodes

I want to loop through all rows in a table and select all in a row.

foreach (var r in Table.SelectNodes("tr"))
{
var Paragraphs = r.SelectNodes("//p");

}


Why do I have have to use SelectNodes("//p") and not just SelectNodes("p")? If I do the later I always get null.

I'm wondering why I don't "//tr" in the foreach statement.

Answer

As such written //p, in this case, it will find "p" nodes located at any depth within the HTML tree of your tr element.

If you write it /p it will search only in the root node of the HTML tree of your tr element

Example:

With //p you will find 2 <p> elements, with only /p you will not find it and null will be return.

<tr>
    <div>
       <p></p>
    </div>
    <div>
       <div>
           <p></p>
       </div>
    <div>

</tr>

In this case, if you search by /p, the element will be found.

<tr>
   <p></p>
</tr>
Comments