0

我正在尝试使用 HTML Agility 包从 html 字符串中获取 som 数据。

我试图从返回 innerhtml 中获取数据的行字符串 [] 如下所示:

<td class="street">Riksdagen</td>
<td class="number">&nbsp;</td>
<td class="number">&nbsp;</td>
<td class="postalcode">100 12</td>
<td class="locality">Stockholm</td>
<td class="region_code">018001</td>
<td class="county">Stockholm</td>
<td class="namnkommun">Stockholm</td>

如何将每个类分配给正确的 addressDataModel 属性?

var row = doc.DocumentNode.SelectNodes("//*[@id='thetable']/tr");

    foreach (var rowItem in row)
    {
        var addressDataModel = new AddressDataModel
        {
            street = rowItem.FirstChild.InnerText,
            zipCodeFrom = // Next item,
            zipCodeTo = // Next item,
            zipCode = // Next item,
            locality = // Next item,
            regionCode = // Next item,
            state = // Next item,
            county = // Next item
        };
    }
4

2 回答 2

1

你可以这样写(确保节点存在之前使用 InnerText 道具):

var addressDataModel = new AddressDataModel
    {
        street = rowItem.SelectSingleNode("./td[@class='street']").InnerText,
        zipCodeFrom = // Next item,
        zipCodeTo = // Next item,
        zipCode = // Next item,
        locality = // Next item,
        regionCode = // Next item,
        state = // Next item,
        county = rowItem.SelectSingleNode("./td[@class='county']").InnerText
    };

参考:http ://www.w3schools.com/xpath/xpath_syntax.asp

于 2013-04-14T21:49:39.413 回答
0

如果您不想使用 Xpath 也可以参考这里:

HtmlAgilityPack.HtmlDocument htmlContent = new HtmlAgilityPack.HtmlDocument();

        htmlContent.LoadHtml(htmlCode);

        if (htmlContent.DocumentNode != null)
        {
            foreach (HtmlNode n in htmlContent.DocumentNode.Descendants("div"))
            {
                if (n.HasAttributes && n.Attributes["class"] != null)
                {
                    if (n.Attributes["class"].Value == "className")
                    {
                      // Do something
                    } 
                }                 
            }
        }
于 2017-04-25T16:44:29.480 回答