这是一个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 :(得分: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;
}