KeyLimeTie Blog

How to safely escape invalid XML characters

By Brian Pautsch – 9/25/2008. Posted to Code Snippets.

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 a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Archives