HTML内容解析

本文关键字:HTML | 更新日期: 2023-09-27 17:54:57

我有两个代码来获得模板内没有字符第一个是

string html = this.GetHTMLContent(url);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
StringBuilder sb = new StringBuilder();
foreach (HtmlTextNode node in doc.DocumentNode.SelectNodes("//text()"))
{
    sb.AppendLine(node.InnerText);
}
string final = sb.ToString();
int lenght = final.Length; 

第二个是

var length = doc.DocumentNode.SelectNodes("//text()")
                .Where(x => x.NodeType == HtmlNodeType.Text)
                .Select(x => x.InnerText.Length)
                .Sum();

当我运行这两个代码返回我不同的结果。

HTML内容解析

最后我发现了问题所在。问题是在循环中我使用了appendLine()方法而不是append()方法。所以每次循环都附加新行。让一些空格也被识别为字符