Why does the XML serializer throw an invalid character exception when the character is inside CDATA?

Possible duplicate:
Why are control characters illegal in XML? Saving 0x1b escape character in XML file

This raises an ArgumentException:

var c = '\x1A'; var xml = new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement("test", new XCData(c.ToString())) ); var foo = xml.ToString(); // ArgumentException 

Why is .Net throwing this exception? I am wrapping an illegal character in CDATA, so I would have thought that illegal characters would be processed for me. This also applies to a group of other characters (e.g. 0x1B, 0x1C, 0x1E, 0x1E, 0x1F).

How do you deal with this problem?

+7
source share
2 answers

I do not think that SecurityElement.Escape will work, because \ x1A is the control code - there is no valid xml object to replace it with.

See the list of valid XML characters for more details.

0
source

Try saving the xml data as shielded data using the SecurityElement from the System.Security namespace. More information can be found here.

 string xmlData = SecurityElement.Escape(xmlData); 

Invalid XML characters can be written by creating an XDocument with the XmlWriterSettings parameter set with the CheckCharacters property to false. This will then replace them with a numeric character, such as # 0; - and # 0x1F. See this article for more details. Alternatively, you can call some xml cleanup method, like this one.

-one
source

All Articles