How to safely escape invalid XML characters

When saving strings to XML, it important to escape invalid characters. The following table shows the invalid XML characters and their escaped equivalents.

Invalid XML Character Replaced With
< &lt;
> &gt;
" &quot;
' &apos;
& &amp;

Rather than write code to do a bunch of replaces, use this one line of code:

1string escapedText = System.Security.SecurityElement.Escape(input);

By using this built-in .NET method, you ensure your strings are properly escaped.

To learn more about this method and see developer's feedback (some people have concerns), go to