HTMLAgilityPack仅迭代所有文本节点

时间:2011-06-14 14:03:27

标签: html-agility-pack

这是一个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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我在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;
    }