Whitelist HTML tags Microsoft Sanitizer and custom Regex I have the following code which I have written due to the fact the Microsoft's Sanitizer is now to aggressive.

What I'm trying to do is as follows.


Create a whitelist of HTML tags I want to keep
After the tags have been converted, run the text through the sanitizer and remove any tags I do not require.
After that, remove any tags that have either id's or classes inside them
Finally convert the tags back. 


My code is below, and it would be much appreciated if someone with more experience can have a look over it and give me some feedback.

string txt = "&lt;h1&gt;Keep as sanitizer removes&lt;/h1&gt;&lt;p&gt;keep&lt;/p&gt;&lt;p class=\"remove\"&gt;remove class&lt;/p&gt;&lt;br/&gt;&lt;script&gt;remove&lt;/script&gt;";
            var whiteList = new List&lt;Word&gt;();
            whiteList.Add(new Word() { SearchWord = "&lt;p&gt;", ReplaceWord = "&amp;lt;p&amp;gt;" });
            whiteList.Add(new Word() { SearchWord = "&lt;/p&gt;", ReplaceWord = "&amp;lt;/p&amp;gt;" });
            whiteList.Add(new Word() { SearchWord = "&lt;h1&gt;", ReplaceWord = "&amp;lt;h1&amp;gt;" });
            whiteList.Add(new Word() { SearchWord = "&lt;/h1&gt;", ReplaceWord = "&amp;lt;/h1&amp;gt;" });
            whiteList.Add(new Word() { SearchWord = "&lt;br/&gt;", ReplaceWord = "&amp;lt;br/&amp;gt;" });

            whiteList.ForEach(w =&gt; txt = txt.Replace(w.SearchWord, w.ReplaceWord));

            var remove = Sanitizer.GetSafeHtmlFragment(txt);

            whiteList.ForEach(w =&gt; remove = remove.Replace(w.ReplaceWord, w.SearchWord));

            var again = RegexHelpers.StripHtmlAttributes(remove);

            var tt = again;



public static string StripHtmlAttributes(string s)
    {
        const string pattern = @"\s.+?=[""'].+?[""']";
        var result = Regex.Replace(s, pattern, string.Empty);
    return result;
}
You could simplify the declaration of the tags you want to keep, as it is very structured:

var whitelist = new List&lt;string&gt;(new string[] { "p", "h1", "br" });

foreach (var w in whitelist) {
  txt = txt.Replace("&lt;" + w + "&gt;", "&amp;lt;" + w + "&amp;gt;")
           .Replace("&lt;" + w + "/&gt;", "&amp;lt;" + w + "/&amp;gt;"));
}

var remove = Sanitizer.GetSafeHtmlFragment(txt);

foreach (var w in whitelist) {
  remove = remove.Replace("&amp;lt;" + w + "&amp;gt;", "&lt;" + w + "&gt;")
                 .Replace("&amp;lt;" + w + "/&amp;gt;", "&lt;" + w + "/&gt;"));
}

var again = RegexHelpers.StripHtmlAttributes(remove);

var tt = again;