C# Escape XML String

There are a lot of XML parsers out there that take a string and attempt to escape out all of the known XML characters. This is usually done when you want to place a user-entered string into XML and don't have much control over the content. I've seen regular expressions and string replaces that do some of this pretty well but many have edge cases they do not cover.

Some have just given up on this and instead used XML's nice "cheat" of placing the text in a CDATA section. Using CDATA, your XML element would like this:

<someElement><![CDATA[My string value that I now do not have to escape]]>

But there is actually a built-in method to the .NET framework that does all of this for you. It is exactly where you would not think to look for it :) Inside: System.Security.SecurityElement.

You can use the class like this:

/// <summary>
/// Escapes the value specified for all XML
/// escape characters.
/// </summary>
/// <param name="value">The value to be escaped.</param>
public static string EscapeXmlString(string value)
{
    return System.Security.SecurityElement.Escape(value);
}