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

As a beginner, I ask that you supply functioning code.

How can I use C# and the html-agility-pack to count the tables in an HTML file?

Based on the number of tables, I will need to get data from a few specified tables in an HTML file. I'll next use the data I've got to do some arithmetic.)

For your convenience, below is an example file with three tables:

<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>

Please SHOW how to transmit the findings to a new text file if you would.

Thanks!

1
0
4/26/2013 11:17:45 PM

Accepted Answer

Possibly 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());
1
4/27/2013 6:06:51 AM

Popular Answer

I consider this to be a good place to start.

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));
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow