Menu Close

C# Html Sanitizer for Windows Phone and Silverlight

By Punit Ganshani

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

Step One: Define the converter


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;
}

}

Step Two: Define converter in XAML

In the XAML file, define

<phone:phoneapplicationpage .Resources>
<converter:htmlsanitizer x:Key="htmlSanitizer" />
</phone:phoneapplicationpage>

Step Three: Use the converter in XAML controls

<textblock  Text="{Binding HtmlText, <strong>Converter={StaticResource htmlSanitizer}}"
TextWrapping="Wrap"  />

Use it otherwise?

You can also give a call

HtmlSanitizer.Convert(inputHtmlString);

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

Posted in Mobile Development, News

Leave a Reply

Your email address will not be published. Required fields are marked *