2010-08-10 2 views
1

안전한 태그 목록에없는 모든 HTML 태그를 제거하는 방법이 있습니까? 없는 경우, 무엇 정규식 그것을 달성하는 방법은 무엇입니까?안전한 목록에없는 HTML 태그를 제거하는 방법

나는 PHP의 strip_tags 함수와 같은 것을 찾고있다.

+0

[RegEx는 XHTML 자체 포함 태그를 제외한 공개 태그와 일치 할 수 있음] (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) –

+0

그게 대체 뭐야? 내 질문에 어떻게 연관 될 수 있습니까? 설명 할 수 있니? – BrunoLM

답변

2

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와 얻을 모든 내부 태그를 제거 태그를 가져옵니다.

+0

나는 투표를 왜 받아 들였는지 모르겠다. – BrunoLM

+0

+1! 하지만 하나의 질문. 왜 '

    '또는 '
  • '은 무시 (체크되지 않은)되지 않습니까? – Janez

    관련 문제