안전한 태그 목록에없는 모든 HTML 태그를 제거하는 방법이 있습니까? 없는 경우, 무엇
정규식
그것을 달성하는 방법은 무엇입니까?안전한 목록에없는 HTML 태그를 제거하는 방법
나는 PHP의
strip_tags
함수와 같은 것을 찾고있다.
안전한 태그 목록에없는 모든 HTML 태그를 제거하는 방법이 있습니까? 없는 경우, 무엇
정규식
그것을 달성하는 방법은 무엇입니까?안전한 목록에없는 HTML 태그를 제거하는 방법
나는 PHP의
strip_tags
함수와 같은 것을 찾고있다.
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와 얻을 모든 내부 태그를 제거 태그를 가져옵니다.
나는 그 글을 좋아한다. 나는 결코 그것에 질려하지 않는다. – kbrimington
완벽한, 그게 내가 필요한 것일뿐입니다. – BrunoLM
당신은 잠재적으로 실행 HTML을 소독하기 위해 MS AntiXSS 라이브러리를 사용할 수 있습니다. 여기에서 살펴 보자 :
[RegEx는 XHTML 자체 포함 태그를 제외한 공개 태그와 일치 할 수 있음] (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) –
그게 대체 뭐야? 내 질문에 어떻게 연관 될 수 있습니까? 설명 할 수 있니? – BrunoLM