剥离不在安全列表中的HTML标记的方法

是否有一种方法可以删除不在安全标签列表中的所有HTML标签? 如果没有,那么实现它的方法是什么样的正则表达式

我正在寻找像PHP的strip_tags函数一样的东西。

做。 不。 使用。 正则表达式。 至。 解析。 HTML。

使用XML解析器:
MSDN参考
简单的教程
HTMLAgilityPack

NullUserException答案是完美的,我做了一个小扩展方法来做到这一点,如果有其他人需要我在这里发帖。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; namespace Extenders { public static class StringExtender { internal static void ParseHtmlDocument(XmlDocument doc, XmlNode root, string[] allowedTags, string[] allowedAttributes, string[] allowedStyleKeys) { XmlNodeList nodes; if (root == null) root = doc.ChildNodes[0]; nodes = root.ChildNodes; foreach (XmlNode node in nodes) { if (!(allowedTags.Any(x => x.ToLower() == node.Name.ToLower()))) { var safeNode = doc.CreateTextNode(node.InnerText); root.ReplaceChild(safeNode, node); } else { if (node.Attributes != null) { var attrList = node.Attributes.OfType().ToList(); foreach (XmlAttribute attr in attrList) { if (!(allowedAttributes.Any(x => x.ToLower() == attr.Name))) { node.Attributes.Remove(attr); } // TODO: if style is allowed, check the allowed keys: values } } } if (node.ChildNodes.Count > 0) ParseHtmlDocument(doc, node, allowedTags, allowedAttributes, allowedStyleKeys); } } public static string ParseSafeHtml(this string input, string[] allowedTags, string[] allowedAttributes, string[] allowedStyleKeys) { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml("" + input + ""); ParseHtmlDocument(xmlDoc, null, allowedTags, allowedAttributes, allowedStyleKeys); string result; using (var sw = new StringWriter()) { using (var xw = new XmlTextWriter(sw)) xmlDoc.WriteTo(xw); result = sw.ToString(); } return result.Substring(6, result.Length - 7); } } } 

使用:

 var x = "allowedallowed attrnot allowed attrnot allowed tag".ParseSafeHtml((new string[] { "b", "#text" }), (new string[] { "class" }), (new string[] { })); 

哪个输出:

 allowedallowed attrnot allowed attrnot allowed tag 

如果不允许该元素,它将获取innerText并拉出标记,删除所有内部标记。

您可以使用MS AntiXSS库来清理可能可执行的HTML。 看看这里:

http://msdn.microsoft.com/en-us/security/aa973814.aspx

http://wpl.codeplex.com/