Caveman's Blog

My commitment to learning.

Replace special characters in XML, using C#

leave a comment »


We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent [1]. The following table shows the invalid XML characters and their respective replacements.

invalid XML Character

Replaced With

“<“

“&lt;”

“>”

“&gt;”

“\””

“&quot;”

“\'”

“&apos;”

“&”

“&amp;”


//Usage
srtXML = SecurityElement.Escape(strXML);

Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)

I have used the HttpUtility classes UrlEncode and UrlDecode methods to handle cross-site scripting attacks and this also helped me to get rid of the XmlException – “Data at the root level is invalid”.

Reference:
1. MSDN

Advertisements

Written by cavemansblog

March 25, 2008 at 8:57 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: