我在 Python 和 Javascript 中找到了类似的问题和答案,但在 C# 或任何其他 WinRT 兼容语言中找不到。
我认为我需要它的原因是因为我在 Windows 8 商店应用程序中显示从网站获得的文本。例如。
é
应该变成é
.
或者有更好的方法吗?我不显示网站或 rss 提要,而只是显示网站及其标题的列表。
我推荐使用 System.Net.WebUtility.HtmlDecode 和 NOT
HttpUtility.HtmlDecode
.
这是因为
System.Web
引用在 Winforms/WPF/Console 应用程序中不存在,您可以使用此类(已作为引用添加到所有这些项目中)获得完全相同的结果。
用法:
string s = System.Net.WebUtility.HtmlDecode("é"); // Returns é
这可能很有用,用它们的 unicode 等效项替换所有(就我的要求而言)实体。
public string EntityToUnicode(string html) {
var replacements = new Dictionary<string, string>();
var regex = new Regex("(&[a-z]{2,5};)");
foreach (Match match in regex.Matches(html)) {
if (!replacements.ContainsKey(match.Value)) {
var unicode = HttpUtility.HtmlDecode(match.Value);
if (unicode.Length == 1) {
replacements.Add(match.Value, string.Concat("&#", Convert.ToInt32(unicode[0]), ";"));
}
}
}
foreach (var replacement in replacements) {
html = html.Replace(replacement.Key, replacement.Value);
}
return html;
}
Metro App和WP8 App中HTML实体和HTML数字的编码/编码不同
{
string inStr = "ó";
string auxStr = System.Net.WebUtility.HtmlEncode(inStr);
// auxStr == ó
string outStr = System.Net.WebUtility.HtmlDecode(auxStr);
// outStr == ó
string outStr2 = System.Net.WebUtility.HtmlDecode("ó");
// outStr2 == ó
}
{
string inStr = "ó";
string auxStr = System.Net.WebUtility.HtmlEncode(inStr);
// auxStr == ó
string outStr = System.Net.WebUtility.HtmlDecode(auxStr);
// outStr == ó
string outStr2 = System.Net.WebUtility.HtmlDecode("ó");
// outStr2 == ó
}
为了解决这个问题,在 WP8 中,我在调用 System.Net.WebUtility.HtmlDecode()
之前在
HTML ISO-8859-1 参考中实现了表格。
这对我有用,替换了通用实体和 unicode 实体。
private static readonly Regex HtmlEntityRegex = new Regex("&(#)?([a-zA-Z0-9]*);");
public static string HtmlDecode(this string html)
{
if (html.IsNullOrEmpty()) return html;
return HtmlEntityRegex.Replace(html, x => x.Groups[1].Value == "#"
? ((char)int.Parse(x.Groups[2].Value)).ToString()
: HttpUtility.HtmlDecode(x.Groups[0].Value));
}
[Test]
[TestCase(null, null)]
[TestCase("", "")]
[TestCase("'fark'", "'fark'")]
[TestCase(""fark"", "\"fark\"")]
public void should_remove_html_entities(string html, string expected)
{
html.HtmlDecode().ShouldEqual(expected);
}
改进的 Zumey 方法(我不能在那里发表评论)。最大字符大小在实体中:&exclamation; (11).实体中的大写字母也是可能的,例如。 À(来自wiki)
public string EntityToUnicode(string html) {
var replacements = new Dictionary<string, string>();
var regex = new Regex("(&[a-zA-Z]{2,11};)");
foreach (Match match in regex.Matches(html)) {
if (!replacements.ContainsKey(match.Value)) {
var unicode = HttpUtility.HtmlDecode(match.Value);
if (unicode.Length == 1) {
replacements.Add(match.Value, string.Concat("&#", Convert.ToInt32(unicode[0]), ";"));
}
}
}
foreach (var replacement in replacements) {
html = html.Replace(replacement.Key, replacement.Value);
}
return html;
}