Saving an escape character 0x1b in an XML file

 ̄綄美尐妖づ 提交于 2020-01-10 04:34:08

问题


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?


回答1:


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




回答2:


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);
}



回答3:


It is impossible to save such values in an XML file. You might need to encode it before hand. You could use Base 64 for this.




回答4:


Maybe you could repalce the ESC char with a special string of your choosing, say "MyEsc123". Before writing the file you replace all instances of 0x1B with the new string and when you read the file you make the conversion again backwords.



来源:https://stackoverflow.com/questions/4134438/saving-an-escape-character-0x1b-in-an-xml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!