我如何在c#解码HTML字符?

我有用HTML字符实体编码的电子邮件地址。.NET中有什么东西可以将它们转换为普通字符串吗?

375871 次浏览

使用Server.HtmlDecode来解码HTML实体。如果你想逃避 HTML,即显示<>字符给用户,使用Server.HtmlEncode

你可以使用HttpUtility.HtmlDecode

如果你正在使用。net 4.0+,你也可以使用WebUtility.HtmlDecode,它不需要额外的程序集引用,因为它在System.Net命名空间中可用。

如果没有服务器上下文(即离线运行),可以使用__abc1 . __abc1。

正如@CQ所说,你需要使用HttpUtility。HtmlDecode,但默认情况下,它在非asp . net项目中不可用。

对于非asp . net应用程序,需要添加对System.Web.dll的引用。在解决方案资源管理器中右键单击项目,选择“添加引用”,然后浏览System.Web.dll的列表。

现在已经添加了引用,您应该能够使用完全限定名System.Web.HttpUtility.HtmlDecode访问该方法,或者为System.Web插入using语句以简化操作。

在。net 4.0上:

System.Net.WebUtility.HtmlDecode()

c#项目不需要包含程序集

值得一提的是,如果你像我一样使用HtmlAgilityPack,你应该使用HtmlAgilityPack.HtmlEntity.DeEntitize()。它接受string并返回string

要解码HTML,请看下面的代码

string s = "Svendborg V&#230;rft A/S";
string a = HttpUtility.HtmlDecode(s);
Response.Write(a);

输出就像

 Svendborg Værft A/S

将static方法写入某个实用程序类,该实用程序类接受string作为参数并返回解码后的html字符串。

using System.Web.HttpUtility包含到类中

public static string HtmlEncode(string text)
{
if(text.length > 0){


return HttpUtility.HtmlDecode(text);
}else{


return text;
}


}

对于。net 4.0

使用using System.Net;System.net.dll的引用添加到项目中,然后使用以下扩展

// Html encode/decode
public static string HtmDecode(this string htmlEncodedString)
{
if(htmlEncodedString.Length > 0)
{
return System.Net.WebUtility.HtmlDecode(htmlEncodedString);
}
else
{
return htmlEncodedString;
}
}


public static string HtmEncode(this string htmlDecodedString)
{
if(htmlDecodedString.Length > 0)
{
return System.Net.WebUtility.HtmlEncode(htmlDecodedString);
}
else
{
return htmlDecodedString;
}
}

对于包含 我必须对字符串进行双重解码。第一次解码会把它变成 第二步将正确解码为预期的字符。