我正在移植一个我编写的Java项目,它使用了Apache Commons Lang的StringEscapeUtils类(特别是
escapeXml
unescapeXml
escapeHtml
unescapeHtml
有没有 .Net 的等效方法?或者也许有一些完全合乎逻辑的 C# 代码可以实现同样的功能吗?
我正在移植一个我编写的Java项目,它使用了Apache Commons Lang的StringEscapeUtils类(特别是
escapeXml
unescapeXml
escapeHtml
unescapeHtml
有没有 .Net 的等效方法?或者也许有一些完全合乎逻辑的 C# 代码可以实现同样的功能吗?
<
和&
等等。转义方法的链接列出了其他项目。public static class StringEscapeUtils
{
public static string EscapeXml(string unescaped)
{
return SecurityElement.Escape(unescaped);
}
public static string UnescapeXml(string escaped)
{
return escaped.Replace("<", "<")
.Replace(">", ">")
.Replace(""", "\"")
.Replace("'", "'")
.Replace("&", "&");
}
public static string EscapeHtml(string unescaped)
{
return HttpUtility.HtmlEncode(unescaped);
}
public static string UnescapeHtml(string escaped)
{
return HttpUtility.HtmlDecode(escaped);
}
}
请查看 HttpServerUtility 类
包括 HttpServerUtility.HtmlEncode、HtmlDecode、UrlDecode 等等...
还有针对 XML 的:
System.Xml.XmlConvert
System.Security.SecurityElement.Escape
Server
对象公开功能并在内部使用HttpUtility。然而,在该上下文之外,您可以直接使用HttpUtility。因此,这取决于您的项目类型和可用性。 - Ahmad MageedHttpServerUtility
上的HtmlEncode
/HtmlDecode
方法是静态的,可以直接调用,不仅仅通过 ASP.NET 中公开的Server
对象。然而,由于这些方法只是直接传递到等效的HttpUtility
方法,因此更合理的做法是直接使用HttpUtility
。 - LukeH