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 = "<h1>Keep as sanitizer removes</h1><p>keep</p><p class=\"remove\">remove class</p><br/><script>remove</script>";
var whiteList = new List<Word>();
whiteList.Add(new Word() { SearchWord = "<p>", ReplaceWord = "<p>" });
whiteList.Add(new Word() { SearchWord = "</p>", ReplaceWord = "</p>" });
whiteList.Add(new Word() { SearchWord = "<h1>", ReplaceWord = "<h1>" });
whiteList.Add(new Word() { SearchWord = "</h1>", ReplaceWord = "</h1>" });
whiteList.Add(new Word() { SearchWord = "<br/>", ReplaceWord = "<br/>" });
whiteList.ForEach(w => txt = txt.Replace(w.SearchWord, w.ReplaceWord));
var remove = Sanitizer.GetSafeHtmlFragment(txt);
whiteList.ForEach(w => 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;
}