HTMLAgilityPack迭代所有文本节点

7

这里有一段HTML代码,我想要的只是获取其中的文本节点并对它们进行迭代。请告诉我如何做。谢谢。

<div>
   <div>
      Select your Age:
      <select>
          <option>0 to 10</option>
          <option>20 and above</option>
      </select>
   </div>
   <div>
       Help/Hints:
       <ul>
          <li>This is required field.
          <li>Make sure select the right age.
       </ul>
      <a href="#">Learn More</a>
   </div>
</div>

结果:

  1. 选择您的年龄:
  2. 0到10岁
  3. 20岁及以上
  4. 帮助/提示:
  5. 这是必填字段。
  6. 确保选择正确的年龄。
  7. 了解更多
2个回答

23

类似这样:

    HtmlDocument doc = new HtmlDocument();
    doc.Load(yourHtmlFile);

    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']"))
    {
        Console.WriteLine(node.InnerText.Trim());
    }

将输出:

Select your Age:
0 to 10
20 and above
Help/Hints:
This is required field.
Make sure select the right age.
Learn More

3

我测试了@Simon Mourier的答案在谷歌首页上,并得到了大量的CSS和Javascript代码,因此我添加了一个额外的过滤器来删除它:

    public string getBodyText(string html)
    {
        string str = "";

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);

        try
        {
            // Remove script & style nodes
            doc.DocumentNode.Descendants().Where( n => n.Name == "script" || n.Name == "style" ).ToList().ForEach(n => n.Remove());

            // Simon Mourier's Answer
            foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']"))
            {
                str += node.InnerText.Trim() + " ";
            }
        }
        catch (Exception)
        {
        }

        return str;
    }

尝试实现您的代码时,我在 n.Remove() 上遇到了“BC30491:表达式不产生值”的错误。 - 8oris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接