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

Rem*_*emy 37 c# html-encode html-entities windows-runtime

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

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

或者,还有更好的方法?我没有显示网站或RSS订阅源,只是列出了网站及其标题.

Bla*_*hma 67

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

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

用法:

string s =  System.Net.WebUtility.HtmlDecode("é"); // Returns é
Run Code Online (Sandbox Code Playgroud)

  • "你可以使用这个类获得完全相同的结果" - INCORRECT.只有HttpUtility实现才能正确解码' 作为WP8上的撇号. (4认同)

小智 11

这可能是有用的,用它们的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;
    }
Run Code Online (Sandbox Code Playgroud)


Mud*_*san 7

使用HttpUtility.HtmlDecode()MSDN上.Read 这里

decodedString = HttpUtility.HtmlDecode(myEncodedString)
Run Code Online (Sandbox Code Playgroud)