C# Html Sanitizer for Xaml

less than 1 minute read

One of the converters that my application developerChannel uses is HtmlSanitizer.  The purpose of this converter is to remove the HTML formatting from a HTML-rich text.

Step One: Define the converter

[sourcecode language='c#']

public class HtmlSanitizer : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return HtmlSanitizer.Convert(value as string);
}

public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}

public static string Convert(string input)
{

// Remove HTML tags and empty newlines and spaces
string returnString = Regex.Replace(input, "< .*?>", "");
returnString = Regex.Replace(returnString, @"n+s+", "nn");

// Decode HTML entities
returnString = HttpUtility.HtmlDecode(returnString);

return returnString;
}

}

[/sourcecode]

Step Two: Define converter in XAML

In the XAML file, define

[sourcecode language='xml']

[/sourcecode]

Step Three: Use the converter in XAML controls

[sourcecode language='xml']

TextWrapping="Wrap"  />

[/sourcecode]

Use it otherwise?

You can also give a call

[sourcecode language='c#']

HtmlSanitizer.Convert(inputHtmlString);

[/sourcecode]

And you are set to go and use this in your applications!

 

 

 

 

 

Updated: