How to get the count of tables in an html file with C# and html-agility-pack

c# html html-agility-pack html-parsing

Question

This is a newbie question so please provide working code.

How do I count the tables in an html file using C# and the html-agility-pack?

(I will need to get values from specific tables in an html file based on the count of tables. I will then perform some math on the values retrieved.)

Here is a sample file with three tables for your convenience:

<html>
<head>
<title>Tables</title>
</head>
<body>
<table border="1">
  <tr>
    <th>Name</th>
    <th>Phone</th>
    <th>City</th>
    <th>Number</th>
  </tr>
  <tr>
    <td>Scott</td>
    <td>555-2345</td>
    <td>Chicago</td>
    <td>42</td>
  </tr>
  <tr>
    <td>Bill</td>
    <td>555-1243</td>
    <td>Detroit</td>
    <td>23</td>
  </tr>
  <tr>
    <td>Ted</td>
    <td>555-3567</td>
    <td>Columbus</td>
    <td>9</td>
  </tr>
</table>
<p></p>
<table border="1">
  <tr>
    <th>Name</th>
    <th>Year</th>
  </tr>
  <tr>
    <td>Abraham</td>
    <td>1865</td>
  </tr>
  <tr>
    <td>Martin</td>
    <td>1968</td>
  </tr>
  <tr>
    <td>John</td>
    <td>1963</td>
  </tr>
</table>
<p></p>
<table border="1">
  <tr>
    <th>Animal</th>
    <th>Location</th>
    <th>Number</th>
  </tr>
  <tr>
    <td>Tiger</td>
    <td>Jungle</td>
    <td>8</td>
  </tr>
  <tr>
    <td>Hippo</td>
    <td>River</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Camel</td>
    <td>Desert</td>
    <td>3</td>
  </tr>
</table>
</body>
</html>

If you would, please SHOW how to send the results to a new text file.

Thanks!

Accepted Answer

Something like this:

HtmlDocument doc = new HtmlDocument();
doc.Load(myTestFile);

// get all TABLE elements recursively
int count = doc.DocumentNode.SelectNodes("//table").Count;

// output to a text file
File.WriteAllText("output.txt", count.ToString());

Popular Answer

I think this can be a starting point

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

var tables = doc.DocumentNode.Descendants("table");
int tablesCount = tables.Count();

foreach (var table in tables)
{
    var rows = table.Descendants("tr")
                    .Select(tr => tr.Descendants("td").Select(td => td.InnerText).ToList())
                    .ToList();

    foreach(var row in rows)
        Console.WriteLine(String.Join(",", row));
}


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