[英]Method to strip HTML tags not in a safe list
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<XmlAttribute>().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("<span>" + input + "</span>");
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 = "<b>allowed</b><b class='text'>allowed attr</b><b id='5'>not allowed attr</b><i>not all<b>o</b>wed tag</i>".ParseSafeHtml((new string[] { "b", "#text" }), (new string[] { "class" }), (new string[] { }));
哪个输出:
<b>allowed</b><b class='text'>allowed attr</b><b>not allowed attr</b>not allowed tag
如果不允许该元素,它将获取innerText并拉出标签,并删除所有内部标签。
您可以使用MS AntiXSS库清除可能执行的HTML。 在这里看一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.