如何从.NET中的文本中删除HTML?

Ron*_*rby 9 .net html c# asp.net jquery

我有一个带有TinyMCE框的asp.net网页.用户可以格式化文本并发送HTML以存储在数据库中.

在服务器上,我想从文本中删除html,这样我只能将文本存储在全文索引列中进行搜索.

使用jQuery的text()函数在客户端上删除html是一件轻而易举的事,但我宁愿在服务器上执行此操作.我可以使用任何现有的实用程序吗?

编辑

看我的回答.

编辑2

替代文字http://tinyurl.com/sillychimp

Ron*_*rby 13

我下载了HtmlAgilityPack并创建了这个函数:

string StripHtml(string html)
{
    // create whitespace between html elements, so that words do not run together
    html = html.Replace(">","> ");

    // parse html
    var doc = new HtmlAgilityPack.HtmlDocument();   
    doc.LoadHtml(html);

    // strip html decoded text from html
    string text = HttpUtility.HtmlDecode(doc.DocumentNode.InnerText);   

    // replace all whitespace with a single space and remove leading and trailing whitespace
    return Regex.Replace(text, @"\s+", " ").Trim();
}
Run Code Online (Sandbox Code Playgroud)


rio*_*era 8

使用正则表达式从字符串中查看此Strip HTML标记

  • 这将删除标签,但保留实体HTML编码,因此它不是一个完整的答案. (3认同)
  • 添加到richardtallent所说的内容:格式错误的HTML可以打破正则表达式并导致它剥离不应该的东西.完整的HTML解析器旨在适应格式错误的HTML,因此您不会丢失数据或获取"额外"数据. (2认同)