C# HTMLAgilityPack count tr elements of first table

c# html-agility-pack

Question

I am using the HTMLAgilityPack for several times. But I have no solution for my following problem:

<table class="tableClass">
  <thead>...</thead>
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

<table class="tableClass">
  <thead>...</thead>
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

So, this is the HTML code.

I can find the first "tableClass" by this:

HtmlNode node= htmlDoc.DocumentNode.SelectSingleNode("//table[@class='tableClass'][1]");

Then, I want to count the elements within the first table.

foreach (HtmlNode tableRow in node.SelectNodes("//tbody//tr"))
 {
     size = size + 1;
 }

The result is always 8 instead of 4.

Please help :/

Thank you very much.

Accepted Answer

1) Do not use // in your XPath if you want to get subnodes of a specific node. use .// instead. do not precede a subnode in your XPath with //:

var trNodes=node.SelectNodes(".//tr");

Popular Answer

Your query for the tr tags is not correct. You are starting it with double slashes, which means, that query will be executed on whole document. If you need to query subnodes, then you need to remove that double slashes from your query

node.SelectNodes("tbody//tr")

Also, you can get count you needed by just one line of code

htmlDoc.DocumentNode.SelectNodes("//table[@class='tableClass'][1]//tbody//tr").Count


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