Because XML syntax uses some characters for tags and attributes it is not possible to directly use those characters inside XML tags or attribute values.
To include special characters inside XML files you must use the numeric character reference instead of that character. The numeric character reference must be UTF-8 because the supported encoding for XML files is defined in the prolog as encoding="UTF-8" and should not be changed.
The numeric character reference uses the format:
&#nn; decimal form
&#xhh; hexadecimal form
We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent [1].
1
2
| //Usage srtXML = SecurityElement.Escape(strXML); |
Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)
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”.
The following table shows the invalid XML characters and their respective replacements.
Code | Name | Displayed as |
	 | Horizontal tab | non-printing |
| Line feed | non-printing |
| Carriage Return | non-printing |
  | Space | non-printing |
! | Exclamation mark | ! |
" | Quotation mark | " |
# | Number sign | # |
$ | Dollar sign | $ |
% | Percent sign | % |
& | Ampersand | & |
' | Apostrophe | ' |
( | Left parenthesis | ( |
) | Right parenthesis | ) |
* | Asterisk | * |
+ | Plus sign | + |
, | Comma | , |
- | Hyphen | - |
. | Period | . |
/ | Slash | / |
: | Colon | : |
; | Semi-colon | ; |
< | Less than | < |
= | Equals sign | = |
> | Greater than | > |
? | Question mark | ? |
@ | At | @ |
[ | Left square bracket | [ |
\ | Bbackslash | \ |
] | Right square bracket | ] |
^ | Caret | ^ |
_ | Underscore | _ |
` | Acute accent | ` |
{ | Left curly brace | { |
| | Vertical bar | | |
} | Right curly brace | } |
~ | Tilde | ~ |
Reference:
1. MSDN
1. MSDN