Friday, November 19, 2010

How to Escape Special Characters in XML from C#

I have written a code which escape special characters in XML while posting an XML Request. Here is the sample code sample.

private string EscapeXMLillegalCharacters (string strValue)
{
    return strValue.Replace("&", "&amp;").Replace("'", "&apos;").Replace("\"", "&quot;").Replace("<", "&lt;").Replace(">", "&gt;");
}

Hope this is useful. Happy coding Smile

2 comments:

  1. Instead of reinvesting the wheel you should write
    string encodedXml = System.Security.SecurityElement.Escape(xml);

    ReplyDelete
    Replies
    1. Yes we can do with what you have suggested. What i did was for the older versions. Thanks and appreciated

      Delete