Sunday, August 01, 2010

How to escape XML text in c#?

Escaping XML text is basically encoding the following symbols (<, >, &, ", ').

This can be done in the following ways.

a) Using Replace function

string xmlData = "I live in \"wellington\" & I love listening to music."
string escapedXmlData = xmlData.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "&apos;");

Note: Replace the & symbol first.

b) Using System.Security.SecurityElement.Escape() method

string xmlData = "I live in \"wellington\" & I love listening to music."

string escapeXmlData = System.Security.SecurityElement.Escape(xmlData);

No comments:

Post a Comment