我有一个方法可以提取超过XX个单词的文本块。问题是它不会返回该文本内部的链接。
我的方法:
public string getAllTextHTML(string _html)
{
string _allText = "";
try
{
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(_html);
document.DocumentNode.Descendants()
.Where(n => n.Name == "script" || n.Name == "style")
.ToList()
.ForEach(n => n.Remove());
RemoveComments(document.DocumentNode);
var root = document.DocumentNode;
var sb = new StringBuilder();
foreach (var node in root.DescendantNodesAndSelf())
{
if (!node.HasChildNodes)
{
string text = node.InnerHtml;
if (!string.IsNullOrEmpty(text))
{
int antalOrd = WordCounting.CountWords1(text);
if (antalOrd > 25)
{
text = System.Web.HttpUtility.HtmlDecode(text);
sb.AppendLine(text.Trim());
}
}
}
}
_allText = sb.ToString();
}
catch (Exception)
{
}
_allText = System.Web.HttpUtility.HtmlDecode(_allText);
return _allText;
}
我怎么能让这也得到文本中的链接?
答案 0 :(得分:1)
我想以下行会产生问题:
if (!node.HasChildNodes)
因为,link(anchor)是htlm标签,你排除了带有锚标签作为孩子的html标签。
以下是返回链接的简单示例:
String html = "<p>asdf<a href='#'>Test</a>asdfasd</p>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
String p = (from x in doc.DocumentNode.Descendants()
where x.Name == "p"
select x.InnerHtml).FirstOrDefault();