6

Possible Duplicate:
Why are “control” characters illegal in XML?
Saving an escape character 0x1b in an XML file

This throws 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'm wrapping the illegal character in CDATA, so I would have thought that illegal characters would be handled for me. This is also the case for a bunch of other characters (e.g. 0x1B, 0x1C, 0x1E, 0x1E, 0x1F).

How do you work around this problem?

Community
  • 1
  • 1
Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275
  • 4
    See these questions: [Saving an escape character 0x1b in an XML file](http://stackoverflow.com/questions/4134438/saving-an-escape-character-0x1b-in-an-xml-file) and [Why are “control” characters illegal in XML?](http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml). Workaraund would be to use Base64 encoding before saving into an XML. – oleksii Feb 27 '12 at 23:51
  • @oleksii You should turn this into an answer, because it's the correct response. – Bevan Feb 28 '12 at 00:22
  • @Bevan: No, actually the question should be closed as a duplicate. – John Saunders Feb 28 '12 at 04:55

2 Answers2

0

I don't think SecurityElement.Escape will work because \x1A is a control code -- there's no valid xml entity to substitute.

See this list of valid XML characters for a bit more detail.

-1

Try storing your xml data as escaped data by using SecurityElement from System.Security namespace. More information can be found here

string xmlData = SecurityElement.Escape(xmlData);

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

Dmitry Savy
  • 1,067
  • 8
  • 22