通过表格的行和列的Html敏捷包环路 [英] Html Agility Pack loop through table rows and columns

查看:219
本文介绍了通过表格的行和列的Html敏捷包环路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表

<table border="0" cellpadding="0" cellspacing="0" id="table2">
    <tr>
        <th>Name
        </th>
        <th>Age
        </th>
    </tr>
        <tr>
        <td>Mario
        </td>
        <th>Age: 78
        </td>
    </tr>
            <tr>
        <td>Jane
        </td>
        <td>Age: 67
        </td>
    </tr>
            <tr>
        <td>James
        </td>
        <th>Age: 92
        </td>
    </tr>
</table>

和希望使用HTML敏捷性包解析它。我曾尝试code无济于事:

And want to use HTML Agility Pack to parse it. I have tried this code to no avail:

foreach (HtmlNode row in doc.DocumentNode.SelectNodes("//table[@id='table2']//tr"))
{
    foreach (HtmlNode col in row.SelectNodes("//td"))
    { 
        Response.Write(col.InnerText); 
    }
}

我是什么做错了吗?

What am I doing wrong?

推荐答案

我必须提供完整的XPath。我用萤火虫从建议由@Coda( http://stackoverflow.com/a/3104048/1238850),我结束了这个code:

I had to provide the full xpath. I got the full xpath by using Firebug from a suggestion by @Coda (http://stackoverflow.com/a/3104048/1238850) and I ended up with this code:

foreach (HtmlNode row in doc.DocumentNode.SelectNodes("/html/body/table/tbody/tr/td/table[@id='table2']/tbody/tr"))
            {
                HtmlNodeCollection cells = row.SelectNodes("td");
                for (int i = 0; i < cells.Count; ++i)
                {
                    if (i == 0)
                    { Response.Write("Person Name : " + cells[i].InnerText + "<br>"); }
                    else {
                        Response.Write("Other attributes are: " + cells[i].InnerText + "<br>"); 
                    }
                }
            }

我相信这可以写成的方式比这更好的,但它是为我工作了。

I am sure it can be written way better than this but it is working for me now.

这篇关于通过表格的行和列的Html敏捷包环路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆