Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an escape character 0x1b in an XML file

Tags:

.net

xml

escaping

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

One of the characters to be sent is an escape character (0x1b). The state of the system and all options changed are later saved in an XML file, but when we try to write the 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 really sure why this arrow functions as escape, but it works on the printer. The error occurs when we try to save it in an XML file. Any suggestions?

like image 271
erikric Avatar asked May 22 '26 12:05

erikric


2 Answers

iSimilar question to:

How do I escape unicode character 0x1F in xml?

So either the not recommended approach of



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

like image 145
Chris Baxter Avatar answered May 25 '26 02:05

Chris Baxter


There is another way to escape such characters by using System.Xml features.

You just need to set 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 to false for XmlReaderSettings if you want to read the xml. :)

using (XmlReader reader = XmlReader.Create(stringReader, new XmlReaderSettings { CheckCharacters = false }))
{
  document = XDocument.Load(reader);
}
like image 31
Vitali Vishneuski Avatar answered May 25 '26 00:05

Vitali Vishneuski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!