2010-08-10 81 views
1

是否有一種方法可以剝離不在安全標籤列表中的所有HTML標籤?如果沒有,那麼 一個正則表達式 的實現方法呢?剝離不在安全列表中的HTML標籤的方法

我正在尋找類似PHP的 strip_tags函數。

+0

[RegEx match open tags not except XHTML self-contained tags]可能重複(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – 2010-08-10 19:04:31

+0

這到底是什麼問題?怎麼可能與我的問題有任何關係?你可以解釋嗎? – BrunoLM 2010-08-10 19:20:26

回答

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 2010-08-13 10:10:46

+0

+1!但有一個問題。爲什麼'

    '或'
  • '被忽略(不會被刪除/檢查)? – Janez 2011-09-05 15:08:34