对,这就是我已经做到的。使用HtmlAgilityPack。 (http://htmlagilitypack.codeplex.com/)
这似乎有点太容易了,让我觉得我已经忽略了可能存在的问题有,但这里是代码:
// Allowed Tags: http://www.w3schools.com/tags/default.asp
string[] allowedTags = { "a", "abbr", "acronym", "address", "applet", "area", "b", "base",
"basefont", "bdo", "big", "blockquote", "body", "br", "button",
"caption", "center", "cite", "code", "col", "colgroup", "dd",
"del", "dfn", "dir", "div", "dl", "dt", "em", "fieldset", "font",
"form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6",
"head", "hr", "html", "i", "iframe", "img", "input", "ins", "isindex",
"kbd", "label", "legend", "li", "link", "map", "menu", "meta",
"noframes", "noscript", "object", "ol", "optgroup", "option", "p",
"param ", "pre", "q", "s", "samp", "script", "select", "small",
"span", "strike", "strong", "style", "sub", "sup", "table", "tbody",
"td", "textarea", "tfoot", "th", "thead", "title", "tr", "tt", "u",
"ul", "var", "xmp" };
HtmlAgilityPack.HtmlDocument fullHtml = new HtmlAgilityPack.HtmlDocument();
fullHtml.LoadHtml(myStringOfHtml);
HtmlAgilityPack.HtmlNodeCollection allNodes = fullHtml.DocumentNode.SelectNodes("//*");
if (allNodes != null)
{
foreach (var item in allNodes)
{
if (!allowedTags.Contains(item.Name))
item.Remove();
}
}
string output1 = fullHtml.DocumentNode.InnerHtml;
让我知道,如果你认为有任何问题这个。我所处理的HTML总是具有结束标签,并且(相对)结构良好,因为它是在将其存储在数据库中之前通过另一家公司编写的自定义HTML检查器完成的。所以我不确定这是如何与格式错误的HTML一起工作的。
感谢Pekka建议采取'搜索和销毁'方法。
正则表达式! http://stackoverflow.com/questions/1732348/#1732454 – 2010-06-06 14:05:52
正则表达式可能是解决方案,但我不知道如何为此写入表达式。我不想删除html,但我想删除它们中的任何控件和html标签(及其内容)。 – James 2010-06-07 09:17:49