HtmlAgilityPack and selecting Nodes and Subnodes

前端 未结 5 1359
轻奢々
轻奢々 2021-01-31 02:12

Hope somebody can help me.

Let´s say I have a html document that contains multiple divs like this example:

5条回答
  •  梦谈多话
    2021-01-31 03:06

    The following works for me. The important bit is just as BeniBela noted to add a dot in second call to 'SelectNodes'.

    List lstRecords=new List();
    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='search_hit']"))
    {
      Record record=new Record();
      foreach (HtmlNode node2 in node.SelectNodes(".//span[@prop]"))
      {
        string attributeValue = node2.GetAttributeValue("prop", "");
        if (attributeValue == "name")
        {
          record.Name = node2.InnerText;
        }
        else if (attributeValue == "company")
        {
          record.company = node2.InnerText;
        }
        else if (attributeValue == "street")
        {
          record.street = node2.InnerText;
        }
      }
      lstRecords.Add(record);
    }
    

提交回复
热议问题