Saving 0x1b escape character in XML file

We have an application that communicates with printers using their internal printer fonts. This requires sending some data in binary format using the font description property.

One of the characters to send is the escape character (0x1b). The system state and all changed parameters are later saved in the XML file, but when we try to write this value, we get the following exception:

System.InvalidOperationException: There is an error in XML document (1009, 26). ---> System.Xml.XmlException: '[Some small backwards arrow symbol]', hexadecimal value 0x1B, is an invalid character. 

I'm not sure why this arrow functions like an escape, but it works on a printer. The error occurs when we try to save it in an XML file. Any suggestions?

+1
source share
4 answers

iDetailed Question:

How to avoid Unicode character 0x1F in xml?

Therefore, either a non-recommended approach

  

or using base-64 as indicated in Darin's answer

+4
source

There is another way to avoid such characters using the System.Xml functions.

You just need to set the CheckCharacters flag to false for XmlWriterSettings.

 using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { CheckCharacters = false })) { document.Save(xmlWriter); } 

But you have to set the same flag as false for XmlReaderSettings if you want to read xml. :)

 using (XmlReader reader = XmlReader.Create(stringReader, new XmlReaderSettings { CheckCharacters = false })) { document = XDocument.Load(reader); } 
+4
source

It is not possible to save such values ​​in an XML file. You may need to code it before hand. You can use Base 64 for this.

+2
source

Perhaps you can return the ESC char with a special string of your choice, say, "MyEsc123". Before writing the file, you replace all instances of 0x1B with a new line, and when you read the file, you do the conversion again.

0
source

All Articles