How to safely escape invalid XML characters

Thursday, September 25, 2008

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
http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(VS.80).aspx

Comments

Leave Comment
Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated. So, please do not use a spammy keyword or a domain as your name, or it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!