将文章的html代码存入到数据库中,读取时不能简单地截取一定字符,必须根据html的结构适当截取内容,否则将显示错误,下面是使用
System.Windows.Forms中的WebBrowser进行Html解析的代码
public string GetAbstract(string content, int maxLength)
{
string text = "";
System.Windows.Forms.HtmlDocument html;
if (content.Length {
text = content;
}
else
{
System.Windows.Forms.WebBrowser browser = new System.Windows.Forms.WebBrowser();
browser.Navigate("about:blank");
html = browser.Document.OpenNew(true);
browser.Dispose();
html.Write(content);
foreach (System.Windows.Forms.HtmlElement ele in html.Body.Children)
{
if (text.Length + ele.OuterHtml.Length { text += ele.OuterHtml; }
else { break; }
}
}
return text;
}
}
本文介绍了一种使用System.Windows.Forms中的WebBrowser组件来解析HTML并根据HTML结构适当地截取部分内容的方法,避免了直接按字符数截取可能导致的HTML结构错误。
2310

被折叠的 条评论
为什么被折叠?



