Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count rows in a table in an html file C#

When there is a compound table inside an html file how can one count the rows of the parent table.

What I mean by a compound table; a table in which other tables are contained within some of its cells.

Here is my attempt at coding. Note I receive an incorrect values:

        String htmlFile = "C:/Temp/Test_13.html";
        HtmlDocument doc = new HtmlDocument();
        doc.Load(htmlFile);

        HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");
        HtmlNodeCollection rows = tables[1].SelectNodes(".//tr");
        Console.WriteLine(" Rows in second (Parent) table: " + rows.Count());

Please indicate which namespace is used in your answer.

Here is a representative sample file:

<html>
<body>
<table border="1">
<tr>
<td>Apps</td>
</tr>
<tr>
<td>Offcie Web Apps</td>
</tr>
</table>
<br/>
<table border="1">
<tr>
<td>Application</td>
<td>Status</td>
<td>Instances</td>
</tr>
<tr>
<td>PowerPoint</td>
<td>Online</td>
<td>
    <table border="1">
    <tr>
        <td>Server1</td>
        <td>Online</td>
    </tr>
    <tr>
        <td>Server2</td>
        <td>Disabled</td>
    </tr>
    </table>
</td>
</tr>
<tr>
<td>Word</td>
<td>Online</td>
<td>
    <table border="1">
    <tr>
        <td>Server1</td>
        <td>Online</td>
    </tr>
    <tr>
        <td>Server2</td>
        <td>Disabled</td>
    </tr>
    </table>
</td>
</tr>
</table>
</body>
</html>

Thank you.

like image 497
user1944272 Avatar asked Dec 10 '25 17:12

user1944272


1 Answers

You can push each <table> and <tr> to the stack and when you encounter </table> - pop until the table is popped from the stack.

like image 102
user2450042 Avatar answered Dec 12 '25 06:12

user2450042



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!