【问题标题】:Html Agility Pack parsing table into objectHtml Agility Pack 将表格解析为对象
【发布时间】:2017-02-17 13:44:29
【问题描述】:

所以我有这样的 HTML:

<tr class="row1">
        <td class="id">123</td>
        <td class="date">2014-08-08</td>
        <td class="time">12:31:25</td>
        <td class="notes">something here</td>
</tr>
<tr class="row0">
        <td class="id">432</td>
        <td class="date">2015-02-09</td>
        <td class="time">12:22:21</td>
        <td class="notes">something here</td>
</tr>

对于每个客户行,它都会继续这样。我想将每个表格行的内容解析为一个对象。我尝试了几种方法,但似乎无法正常工作。

这是我目前拥有的

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
foreach (HtmlNode row in doc.DocumentNode.SelectNodes("//table[@id='customerlist']//tr"))
{
    Customer cust = new Customer();
    foreach (HtmlNode info in row.SelectNodes("//td"))
    {
        if (info.GetAttributeValue("class", String.Empty) == "id")
        {
            cust.ID = info.InnerText;
        }
        if (info.GetAttributeValue("class", String.Empty) == "date")
        {
            cust.DateAdded = info.InnerText;
        }
        if (info.GetAttributeValue("class", String.Empty) == "time")
        {
            cust.TimeAdded = info.InnerText;
        }
        if (info.GetAttributeValue("class", String.Empty) == "notes")
        {
            cust.Notes = info.InnerText;
        }
    }
    Console.WriteLine(cust.ID + " " + cust.TimeAdded + " " + cust.DateAdded + " " + cust.Notes);
}

它的工作原理是在每个循环中打印表格的最后一行的信息。我只是错过了一些非常简单的东西,但看不到什么。

我创建对象的方式也很好,还是应该使用构造函数并从变量创建对象?例如

    string Notes = String.Empty;
if (info.GetAttributeValue("class", String.Empty) == "notes")
{
    Notes = info.InnerText;
}
..
Customer cust = new Customer(id, other_variables, Notes, etc);

【问题讨论】:

    标签: c# foreach html-parsing html-agility-pack


    【解决方案1】:

    您的 XPath 查询错误。您需要使用td 而不是//td

    foreach (HtmlNode info in row.SelectNodes("td"))
    

    //td 传递给SelectNodes() 将匹配文档中的所有 &lt;td&gt; 元素,因此您的内部循环运行8 次而不是4 次,最后4 次总是覆盖这些值之前在您的 Customer 对象中设置。

    XPath Examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2014-07-13
      相关资源
      最近更新 更多