【问题标题】:Get specific element inside other element with HtmlAgilityPack in C#在 C# 中使用 HtmlAgilityPack 获取其他元素内的特定元素
【发布时间】:2013-05-05 19:57:50
【问题描述】:

我正在处理一个需要解析大量 html 文件的项目。我需要从一个<div class="story-body"> 中获取每个<p>

到目前为止,我有这段代码,它可以满足我的要求,但我想知道如何使用 xpath 表达式来做到这一点。我试过这个:

textBody.SelectNodes ("What to put here? I tried //p but it gives every p in document not inside the one div")

但没有成功。有什么想法吗?

public void Parse(){
   HtmlNode title = doc.DocumentNode.SelectSingleNode ("//h1[(@class='story-header')]");
   HtmlNode textBody = doc.DocumentNode.SelectSingleNode ("//div[(@class='story-body')]");

   XmlText textT;
   XmlText textS;

   string story = "";

   if(title != null){
     textT = xmlDoc.CreateTextNode(title.InnerText);
     titleElement.AppendChild(textT);
     Console.WriteLine(title.InnerText);
   }

   foreach (HtmlNode node in textBody.ChildNodes) {
      if(node.Name == "p" || (node.Name == "span" && node.GetAttributeValue("class", "class") == "cross-head")){
         story += node.InnerText + "\n\n";
         Console.WriteLine(node.InnerText);
      }
   }

   textS = xmlDoc.CreateTextNode (story);

   storyElement.AppendChild (textS);

   try
   {
        xmlDoc.Save("test.xml");            
   }
   catch (Exception e)
   {
        Console.WriteLine(e.Message);
   }
}

【问题讨论】:

    标签: c# html mono


    【解决方案1】:

    这是一件相当简单的事情,您只需将. 添加到.//p 之类的字符串中,这样您就可以获得当前节点的子节点。

    另一种方法是像这样调用 SelectNodes:

    doc.DocumentNode.SelectNodes("//div[(@class='story-body')]/p");
    

    【讨论】:

    • 谢谢,你说得对,这很简单。但是我以我原来的方法结束,因为我必须检查更多的东西,我认为它不能用 xpath 实现
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2014-09-16
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多