HTMLAgilityPack解析另一个表格单元格中的表格

时间:2014-08-08 20:06:26

标签: c# arraylist html-agility-pack

我有下表:

<table>
    <tr><th>header1</th><th>header2</th><th>header3</th></tr>
    <tr><td>value01</td><td>value02</td><td>value03</td></tr>
    <tr><td>value11</td><td>value12</td><td>value13</td></tr>
    <tr>
        <td colspan="3">
            <table>
                <tr><td>subvalue01</td><td>subvalue02</td></tr>
            </table>
        </td>
    </tr>
</table>

我使用此代码将主表格单元格值保存到另一个ArrayList中的单独ArrayList和子表单元格值中。但我的ArrayList子表单元格值保存了整个值,包括表和子表:

foreach (HtmlNode table in hdoc.DocumentNode.SelectNodes("//table"))
{
    ///This is the table.
    foreach (HtmlNode row in table.SelectNodes("tr").Skip(1))
    {
        ///This is the row.
        foreach (HtmlNode cell in row.SelectNodes("th|td")) 
            ///can also use "th|td", but right now we ONLY need td
        {
            //This is the cell.
            if (cell.InnerHtml.Contains("<table>"))
            {
                foreach (HtmlNode subtable in cell.SelectNodes("//table"))
                {
                    foreach (HtmlNode subrow in subtable.SelectNodes("tr").Skip(1))
                    {
                        foreach (HtmlNode subcell in subrow.SelectNodes("th|td"))
                        {
                            arrSubList.Add(subcell.InnerText);
                        }
                    }
                }
            }
            else
            {
                arrList.Add(cell.InnerText);
            }
        }
    }
}

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

我相信你的第一行

foreach (HtmlNode table in hdoc.DocumentNode.SelectNodes("//table"))

将选择所有表 - 在任何级别(包括嵌套表)。

Per:http://www.w3schools.com/XPath/xpath_syntax.asp

  

//从当前节点中选择与文档匹配的节点   选择无论他们在哪里

所以,将第一行改为

foreach (HtmlNode table in hdoc.DocumentNode.SelectNodes("/html/body/table"))

看看情况如何。