Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

c# - HTMLAgilityPack parse in the InnerHTML

<div>
<b>Token1</b>
Token2
<b>Token3</b>
</div>

I try to extract Token2 from the div

I manage to get Token1 and Token3 with :

HtmlNodeCollection headerFooter = doc.DocumentNode.SelectNodes("//div//b");

How can I extract directly Token2 with HTMLAgilityPack ?

One dirty option is to replace Token1 and Token2 by string.empty in doc.DocumentNode.SelectNodes("//div").InnerText, but I imagine it can been done in more clean way with HTMLAgilityPack...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The text is in the text nodes; so you should be able to look at "//div/text()" and concatenate:

StringBuilder sb = new StringBuilder();
foreach (HtmlAgilityPack.HtmlTextNode node in
      doc.DocumentNode.SelectNodes("//div/text()"))
{
    sb.Append(node.Text.Trim());
}
string s = sb.ToString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...