我想使用HTML敏捷包解析HTML表格。我想从表中仅提取一些预定义的列数据。

不过,我是新来解析和HTML敏捷性包,我都试过,但我不知道如何使用HTML敏捷性包我的需要。

如果有人知道然后如果可能的话给我示例

修改

是否可以解析HTML表格一样,如果我们只想提取的决定列名数据?像有4列的名称,地址,和PHNO我想只提取姓名和地址数据。

有帮助吗?

解决方案

有是这样一个例子中讨论论坛此处 。向下滚动一点看表的答案。我也希望他们能提供更好的样品是比较容易找到。

编辑: 为了从特定的列数据,你必须先找到对应于您想要的列的<th>标签和记住他们的索引。那么你就需要找到相同的索引<td>标签。假设你知道列的索引,你可以做这样的事情:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("http://somewhere.com");
HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
foreach (var row in table.SelectNodes("//tr"))
{
    HtmlNode addressNode = row.SelectSingleNode("td[2]");
    //do something with address here
    HtmlNode phoneNode = row.SelectSingleNode("td[5]");
    // do something with phone here
}

EDIT2: 如果你不知道列的索引,你可以做这样整个事情。我还没有测试此。

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("http://somewhere.com");
var tables = doc.DocumentNode.SelectNodes("//table");

foreach(var table in tables)
{
    int addressIndex = -1;
    int phoneIndex = -1;
    var headers = table.SelectNodes("//th");
    for (int headerIndex = 0; headerIndex < headers.Count(); headerIndex++)
    {
        if (headers[headerIndex].InnerText == "address")
        {
            addressIndex = headerIndex;
        }
        else if (headers[headerIndex].InnerText == "phone")
        {
            phoneIndex = headerIndex;
        }
    }

    if (addressIndex != -1 && phoneIndex != -1)
    {
        foreach (var row in table.SelectNodes("//tr"))
        {
            HtmlNode addressNode = row.SelectSingleNode("td[addressIndex]");
            //do something with address here
            HtmlNode phoneNode = row.SelectSingleNode("td[phoneIndex]");
            // do something with phone here
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top