当前位置: 首页 > 编程语言 > C#

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

时间:2023-04-11 11:40:35 C#

C#学习教程:在C#中将HTML实体转换为Unicode字符我认为我需要它的原因是因为我在Windows8商店应用程序中显示从网站获得的文本。例如é应该变成é。或者,还有更好的方法?我没有显示网站或RSS提要,而是显示网站列表及其标题。我推荐使用System.Net.WebUtility.HtmlDecode而不是HttpUtility.HtmlDecode。这是因为System.Web引用在Winforms/WPF/Console应用程序中不存在,您可以使用此类(在所有这些项目中作为引用添加)来获得完全相同的结果。用法:字符串s=System.Net.WebUtility.HtmlDecode("é");//Returnsé这可能很有用,可以用它们的unicode等效项替换所有(根据我的要求)实体。publicstringEntityToUnicode(stringhtml){varreplacements=newDictionary();varregex=newRegex("(&[az]{2,5};)");foreach(在regex.Matches(html)中匹配匹配){if(!replacements.ContainsKey(match.Value)){varunicode=HttpUtility.HtmlDecode(match.Value);如果(unicode.Length==1){replacements.Add(match.Value,string.Concat("&#",Convert.ToInt32(unicode[0]),";"));}}}foreach(替换中的var替换){html=html.Replace(replacement.Key,replacement.Value);}返回html;在msdn上使用HttpUtility.HtmlDecode()。读取decodedString=HttpUtility.HtmlDecode(myEncodedString)MetroApp和WP8App中HTML实体和HTML数字的不同编码/编码。使用WindowsRuntimeMetroApp{stringinStr="ó";字符串auxStr=System.Net.WebUtility.HtmlEncode(inStr);//auxStr==óstringoutStr=System.Net.WebUtility.HtmlDecode(auxStr);//outStr==óstringoutStr2=System.Net.WebUtility.HtmlDecode("ó");//outStr2==ó}使用WindowsPhone8.0{stringinStr="ó";字符串auxStr=System.Net.WebUtility.HtmlEncode(inStr);//auxStr==óstringoutStr=System.Net.WebUtility.HtmlDecode(auxStr);//outStr==óstringoutStr2=System.Net.WebUtility.HtmlDecode("ó");//outStr2==ó}为了解决这个问题,在WP8中,我在调用System.Net.WebUtility.HtmlDecode()之前实现了HTMLISO-8859-1参考中的表格。这对我有用,替换了普通实体和unicode实体。privatestaticreadonlyRegexHtmlEntityRegex=newRegex("&(#)?([a-zA-Z0-9]*);");publicstaticstringHtmlDecode(thisstringhtml){if(html.IsNullOrEmpty())返回html;返回HtmlEntityRegex.Replace(html,x=>x.Groups[1].Value=="#"?((char)int.Parse(x.Groups[2].Value)).ToString():HttpUtility.HtmlDecode(x.Groups[0].Value));}[测试][TestCase(null,null)][TestCase("","")][TestCase("'fark'","'fark'")][TestCase(""fark"",""fark"")]publicvoidshould_remove_html_entities(stringhtml,stringexpected){html.HtmlDecode().ShouldEqual(expected);}改进的Zumey方法(我无法评论)。实体中的最大字符大小:&exclamation;(11).实体中的资本化也是可能的,例如。à(来自维基百科)以上是C#学习教程:ConvertingHTMLEntitiestoUnicodeCharactersinC#。如果对你有用,需要进一步了解《C#学习教程》,希望大家多多关注——publicstringEntityToUnicode(stringhtml){varreplacements=newDictionary();varregex=newRegex("(&[a-zA-Z]{2,11};)");foreach(在regex.Matches(html)中匹配匹配){if(!replacements.ContainsKey(match.Value)){varunicode=HttpUtility.HtmlDecode(match.Value);如果(unicode.Length==1){replacements.Add(match.Value,string.Concat("&#",Convert.ToInt32(unicode[0]),";"));}}}foreach(替换中的var替换){html=html.Replace(replacement.Key,replacement.Value);}返回html;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢