Is there an implementation of org.apache.commons.lang.StringEscapeUtils for .Net?
I'm porting over a Java project that I wrote which uses the Apache Commons Lang StringEscapeUtils class (particularly the
escapeXml
unescapeXml
escapeHtml
unescapeHtml
methods). Is there a .Net equivalent? Or perhaps some totally logical bit of C# code that accomplishe开发者_Python百科s the same thing?
Using System.Web for HTML there is:
- HttpUtility.HtmlEncode
- HttpUtility.HtmlDecode
For XML escaping you can use the SecurityElement.Escape method in the System.Security namespace. However, there's no equivalent to unescape it that I am aware of. You would have to write your own method that replaces the encoded XML, such as <
and &
etc. with their equivalents. The link for the escape method lists the other items.
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);
}
}
You could use the HtmlEncode and HtmlDecode for the Html replacements. Your options for XML escaping can be found here.
Check out HttpServerUtility Class
HttpServerUtility.HtmlEncode, HtmlDecode, UrlDecode etc etc...
Also for XML:
System.Xml.XmlConvert
System.Security.SecurityElement.Escape
精彩评论