HtmlAgilityPack select nodes on first level

html-agility-pack

Question

Consider the following HTML

<tr>
  <td>1</td>
  <td>2</td>
  <td>
    <table>
      <tbody>
        <tr>
          <td>3</td>
          <td>4</td>
        </tr>
      <tbody>
    </table>
  </td>
  <td>5</td>
</tr>

What I want here is to take all <td> elements which are direct descendants to the main <tr> row. Which means, I want to take 1, 2 and 5.

The code I am using

gridRow.Descendants("td")

will return all <td> elements below the main <tr> node.

Does HtmlAgilityPack provide the functionality to get first level descendants (because I can't find such method) ?

Accepted Answer

HtmlNode.Elements("child_name") is exactly what you are looking for :

gridRow.Elements("td")

Popular Answer

Ok, I think this will work:

 gridRow.Descendants("td").Where(x => x.ParentNode == gridRow)

This will return all <td> elements, whose direct parent is the main <tr> element.



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