How can I make xmldataprovider process escaped characters?
I have built a very simple XAML RSS reader in WPF, using the XMLDataProvider to get the RSS data. That XAML looks like this:
<XmlDataProvi开发者_JS百科der x:Key="rssData" XPath="//item" Source="http://www.theglobeandmail.com/?service=rss" IsAsynchronous="True" IsInitialLoadEnabled="True" />
Then, I display the description provided by the RSS feed inside a ListItemTemplate like this (irrelevant details elided):
<TextBlock TextWrapping="Wrap" Text="{Binding XPath=description}"/>
The problem is that any escaped characters in the description come through un-processed. ie: Open letter denounces mayor&146;s plan, etc, etc.
The &146; of course, should be converted to an apostrophe. I could write a binding converter to do this reasonably easily, but I don't think I should have to. What simple thing am I missing?
Thanks in advance for any help.
I'm still hoping that there is a better way, but for now I implemented a value converter, used an HTML decoder and then manually fix characters &145; through &149;. I'm open to better solutions, though!
public class HTMLEscapedCharactersConverter : IValueConverter
{
private static readonly char[] MapChars = {'\x091', '\x092', '\x093', '\x094'};
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var htmlText = value as string;
if (!string.IsNullOrEmpty(htmlText))
{
htmlText = System.Net.WebUtility.HtmlDecode(htmlText);
if (htmlText.IndexOfAny(MapChars) > 0)
{
var decodedText = new StringBuilder(htmlText.Length);
foreach (var ch in htmlText)
switch (ch)
{
// Windows Code page 1252: http://en.wikipedia.org/wiki/Windows-1252
case '\x091':
decodedText.Append('\x2018');
break;
case '\x092':
decodedText.Append('\x2019');
break;
case '\x093':
decodedText.Append('\x201C');
break;
case '\x094':
decodedText.Append('\x201D');
break;
default:
decodedText.Append(ch);
break;
}
return decodedText.ToString();
}
}
return htmlText ?? String.Empty;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var s = value as string;
if (s != null)
{
s = WebUtility.HtmlEncode(s);
}
return s ?? String.Empty;
}
}
精彩评论