Skip to content

Question: sanitise HtmlNodeType.Text ie replace smart quotes with simple quote... #38

Description

@mistyn8

Question: sanitise HtmlNodeType.Text ie replace smart quotes with simple quote...
Is the following a reasonable way to do this? (though would like not to have to explicitly set on all the tags...)

public class CharReplacementSanitizer : IHtmlElementSanitizer
 {
     public SanitizerOperation SanitizeElement(HtmlNode element, HtmlSanitizerTagRule tagRule)
     {
         if (element.HasChildNodes)
         {
             for (int i = element.ChildNodes.Count - 1; i >= 0; i--)
             {
                 HtmlNode child = element.ChildNodes[i];
                 if (child.NodeType == HtmlNodeType.Text)
                 {
                     string updatedText = child.InnerText.Replace("’", "'");
                     HtmlNode newChild = HtmlNode.CreateNode(HtmlEntity.DeEntitize(updatedText));
                     element.ReplaceChild(newChild, child);
                 }
             }
         }
         else
         {
             element.InnerHtml = element.InnerHtml.Replace("’", "'");
         }

         return SanitizerOperation.DoNothing;
     }
 }

 var sanitizer = new HtmlSanitizer();
 
 sanitizer.EncodeHtmlEntities = true;
 sanitizer.Tag("div").NoAttributes(SanitizerOperation.FlattenTag);
 sanitizer.Tag("a").NoAttributes(SanitizerOperation.FlattenTag).Sanitize(new CharReplacementSanitizer());
 sanitizer.Tag("p").Sanitize(new CharReplacementSanitizer()).RemoveEmpty();
 sanitizer.Tag("br");
 sanitizer.Tag("ul");
 sanitizer.Tag("li").Sanitize(new CharReplacementSanitizer());
 sanitizer.Tag("strong").Sanitize(new CharReplacementSanitizer()).RemoveEmpty();
 sanitizer.Tag("em").Sanitize(new CharReplacementSanitizer()).RemoveEmpty();
 sanitizer.Tag("b").Rename("strong").Sanitize(new CharReplacementSanitizer()).RemoveEmpty();
 sanitizer.Tag("i").Rename("em").Sanitize(new CharReplacementSanitizer()).RemoveEmpty();

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions