在C#中将HTML实体转换为Unicode字符

我发现Python和Javascript的类似问题和答案,但不适用于C#或任何其他WinRT兼容语言。

我认为我需要它的原因是因为我正在显示我从Windows 8商店应用程序中的网站获得的文本。 例如é 应该成为é

或者,还有更好的方法? 我不是显示网站或RSS订阅源,而是显示网站及其标题列表。

我建议使用System.Net.WebUtility.HtmlDecodeNOT HttpUtility.HtmlDecode

这是因为Winforms / WPF / Console应用程序中不存在System.Web引用,并且您可以使用此类(在所有这些项目中已添加为引用)获得完全相同的结果。

用法:

 string s = System.Net.WebUtility.HtmlDecode("é"); // Returns é 

这可能很有用,用它们的unicode等效替换所有(对于我的要求去)实体。

  public string EntityToUnicode(string html) { var replacements = new Dictionary(); var regex = new Regex("(&[az]{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; } 

在msdn上使用HttpUtility.HtmlDecode() 。阅读

 decodedString = HttpUtility.HtmlDecode(myEncodedString) 

Metro App和WP8 App中HTML实体和HTML编号的不同编码/编码。

使用Windows Runtime Metro App

 { 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 == ó } 

使用Windows Phone 8.0

 { 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 Reference中实现了该表。

这对我有用,取代了普通和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)。 实体中的大写也是可能的,例如。 À(来自维基 )

 public string EntityToUnicode(string html) { var replacements = new Dictionary(); 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; }