views:

454

answers:

4

Is there any 'slimmer' alternative to the System.Web.HttpUtility.HtmlEncode/.Decode functions in .net 3.5 (sp1)? A separate library is fine.. or even 'wanted', at least something that does not pull in a 'whole new world' of dependencies that System.Web requires.

I only want to convert a normal string into its xml/xhtml compliant equivalent (& back).

A: 

For XML you just have to encode the characters that have a special meaning, so you could get away with something simple like:

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;", "&");
}
Guffa
My Q wasn't actually entirely clear, but that -was- my usecase. Thanks!
Jörg B.
That `XmlDecode` doesn't even begin to cover XML's character and entity references (http://www.w3.org/TR/xml/#sec-references), nevermind `CDATA` sections etc.
Josef
+1  A: 

If possible you can "borrow" the HttpUtility class from Mono code and compile it directly a your utility assembly.

munissor
+1  A: 

Although encoding might seem simple, I strongly recommend to use a library that is in wide-spread use to minimize the risk of security vulnerabilities. Microsoft's Anti-Cross Site Scripting Library provides methods for Html/Xml/Javascript escaping and the respective attribute escapes and should cover most of your web needs.

Josef
+2  A: 

In .NET Framework 4.0, System.Net.WebUtility.HtmlEncode perhaps? Do note that this class is located in System.dll and not System.Web.dll.

Ion Todirel