HTMLAgilityPack仅迭代所有文本节点

| 这是一个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>
结果: 选择您的年龄: 0至10 20以上 帮助/提示: 这是必填字段。 确保选择正确的年龄。 学到更多     
已邀请:
        像这样:
    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
    
        我在Google主页上测试了@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;
    }
    

要回复问题请先登录注册