System.Web.HttpUtility.HtmlEncode/Decode的替代品?

Jör*_*ann 4 .net entities html-entities

.net 3.5(sp1)中的System.Web.HttpUtility.HtmlEncode/.Decode函数是否有"更瘦"的替代方案?一个单独的库是好的...甚至是"想要的",至少是一些不会引入System.Web所需的"全新"依赖关系的东西.

我只想将普通字符串转换为符合xml/xhtml的等效字符串(&back).

Ion*_*rel 26

在.NET Framework 4.0中,System.Net.WebUtility.HtmlEncode也许?请注意,此类位于System.dll而不是System.Web.dll.


Guf*_*ffa 5

对于XML,您只需要对具有特殊含义的字符进行编码,这样您就可以使用以下简单的方法:

public static string XmlEncode(string value) {
  return value
    .Replace("<", "&lt;")
    .Replace(">", "&gt;")
    .Replace("\"", "&quot;")
    .Replace("'", "&apos;")
    .Replace("&", "&amp;");
}

public static string XmlDecode(string value) {
  return value
    .Replace("&lt;", "<")
    .Replace("&gt;", ">")
    .Replace("&quot;", "\"")
    .Replace("&apos;", "'")
    .Replace("&amp;", "&");
}
Run Code Online (Sandbox Code Playgroud)

  • 那个`XmlDecode`甚至没有开始涵盖XML的字符和实体引用(http://www.w3.org/TR/xml/#sec-references),从不涉及`CDATA`部分等. (2认同)