循环遍历元素并定义行/列

时间:2013-09-10 19:49:50

标签: c# html xpath matrix html-agility-pack

我有一个HTML <td>元素的HtmlNodeCollection,我是使用HTMLAgilityPack从表中收集的。通常,我只需选择表中的<tr>元素并循环遍历<td>元素,但不幸的是<tr>开始标记是通过JavaScript生成的,不会从服务器呈现。我无法控制HTML的呈现方式。因此,我从这个XPATH查询中获取了一个HtmlNodeCollection:

HtmlNode table = htmlDoc.DocumentNode.SelectSingleNode("//table[@width='100%' and @cellpadding='1' and @cellspacing='1' and @border='0']");
HtmlNodeCollection tds = table.SelectNodes(".//td[@align and string-length(@width)=0]"); // only select td elements that have the align attribute and don't have a width attribute

在表格中,有六列和任意数量的行。我想处理每一行并将列解析为中间数据结构。我有这个代码来获取每个“行”和“列”,但它不太正确:

int cols = 6; // six columns
int rows = tds.Count / cols;

// loop through the rows
for (int row = 1; row <= rows; row++)
{
    for (int col = 0; col < cols; col++)
    {
        HtmlNode td = tds[col * row]; // get the associated td element from the column index * row index
        MessageBox.Show(td.InnerHtml + "\n" + td.InnerText);
    }
}

我从第1行而不是第0行开始并以行计数结束,因为我不想将零乘以6。我试图将其视为一个矩阵,但是我很难定义一行何时结束而下一行开始。您对如何正确遍历所有行和列有任何建议吗?

1 个答案:

答案 0 :(得分:0)

在纸上画出一个网格后,很明显我错过了什么。我需要将列索引添加到列数乘以当前行,如下所示:

for (int row = 0; row < rows; row++)
{
    for (int col = 0; col < cols; col++)
    {
        HtmlNode td = tds[col + cols * row]; // get the associated td element from the column index * row index
        MessageBox.Show(td.InnerHtml + "\n" + td.InnerText);
    }
}