2010-08-20 33 views

回答

1

對整個字符串進行編碼,然後解碼您不想編碼的特定標籤。

如果您只允許沒有任何屬性的簡單標籤(例如<b><u>),那麼您可以使用簡單的Replace對它們進行解碼。

1

假設您的輸入HTML是格式良好的,您可以使用正則表達式。這是可能的,因爲您不是試圖在嵌套標籤中查找匹配對,而且您並不擔心HTML註釋中出現的標籤。否則,正則表達式將成爲這項工作的一個不好的候選人。

var allowedTags = new[] { "a", "abbr", "br", /* etc. */ }; 

var output = Regex.Replace(input, 
    // Matches a single start or end tag 
    @"</?(\w+)[^>]*>", 
    // If the tag is one of the allowed tags... 
    me => allowedTags.Contains(me.Groups[1].Value) 
     // ... keep it unchanged 
     ? me.Value 
     // otherwise, HTML-encode it 
     : HttpServerUtility.HtmlEncode(me.Value), 
    RegexOptions.Singleline); 

如果您的HTML來自用戶,那麼您不能認爲它是格式良好的。在這種情況下,我會推薦一個更強大的解決方案,例如使用Html Agility Pack