We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent. The following table shows the invalid XML characters and their respective replacements
| Character Name | Entity Reference | Character Reference | Numeric Reference |
|---|---|---|---|
| Ampersand | & | & | & |
| Left angle bracket | < | < | &#60; |
| Right angle bracket | > | > | > |
| Straight quotation mark | " | " | ' |
| Apostrophe | ' | ' | " |
Sample Usage of this Escape method.
//Usage
srtXML = SecurityElement.Escape(strXML);
For this you need to import System.Security namespace. Alternatively you can also use this simple replace method with all special characters in a single method like below
public string EscapeXml(string s) { string toxml = s; if (!string.IsNullOrEmpty(toxml)) { // replace special chars with entities toxml = toxml.Replace("&", "&"); toxml = toxml.Replace("'", "'"); toxml = toxml.Replace("\"", """); toxml = toxml.Replace(">", ">"); toxml = toxml.Replace("<", "<"); } return toxml; }
Hope this is useful!