如何在html文件中计算表的行数

本文关键字:计算 html 文件 | 更新日期: 2023-09-27 18:16:36

当html文件中有一个复合表时,如何计算父表的行数

我所说的复合表是什么意思?在其中的一些单元格中包含其他表的表。

这是我的编码尝试。注意,我收到一个不正确的值:

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

请指出答案中使用的名称空间

下面是一个代表性的示例文件:

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

谢谢。

如何在html文件中计算表的行数

您可以将每个<table><tr>推入堆栈,当遇到</table>时- pop直到表从堆栈中弹出

我建议您尝试csQuery nuget包。它的设计是为了消除做这种事情时的大部分头痛。你可以使用css选择器查询语法,大多数web开发人员都非常熟悉。在这种情况下,您可能会使用body > table:nth-of-type(2) > tr,它将返回所有tr的数组,然后对它们进行计数,或者检查结果数组的长度。或者,body > table ~ table > tr也可以从您提供的示例中工作,br + table > tr

如果我没理解错的话,这就是你想要的。

int i = 1;
HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");
foreach (HtmlNode table in tables)
{
    var tmp = table.ParentNode;
    if (tmp.OriginalName.Contains("td"))
        MessageBox.Show("The parent of table #" + i + " has" + tmp.ParentNode.ParentNode.Elements("tr").Count().ToString() + " rows.");
    i++;
}

消息框将弹出2次:

"The parent of table #3 has 3 rows."
"The parent of table #4 has 3 rows."

编辑(回答问题):

1)我从int i = 1开始计数。var i = 1也是一样的,它只是自动将var替换为int

2)我编辑的代码,现在你会有相同的结果与我

3)我从1开始计数,所以你有表1、表2、表3和表4。最后两个表(表#3和表#4)是表#2的子表,表#2有3行。我上面的代码只打印表是一些表的子表。你能告诉我你想要的答案吗?

编辑2:

int i = 1;
HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");
foreach (HtmlNode table in tables)
{
    if (!table.ParentNode.OriginalName.Contains("td")) // If table is not sub-table
        MessageBox.Show("Table #" + i + " have " + table.Elements("tr").Count().ToString() + " rows.");
    i++;
}

消息框将弹出2次:

"The parent of table #1 has 2 rows."
"The parent of table #2 has 3 rows."