對,這就是我已經做到的。使用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