我有这段代码来保存一些配置数据
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Entities.Application));
TextReader textReader = new StreamReader(XMLFile);
sequences = (Entities.Application)xmlSerializer.Deserialize(textReader);
textReader.Close();
现在我希望稍微隐藏它并以某种方式使用XML上的二进制格式(无论如何都要保留XML)。
有可能吗? (或者还有其他一些方法?)
如何做到这一点?
谢谢!
答案 0 :(得分:1)
您仍然需要将二进制数据编码为文本。它已经被压缩了吗?如果是这样,那可能是第一步。然后,您需要决定如何编码二进制文件。 Base91非常有效:http://base91.sourceforge.net/
答案 1 :(得分:1)
如果您想隐藏XML,那么两个简单的选项是使用Base64编码XML或在XML元素中使用Base64。
// Simple Base64 conversion (using UTF8 for simplicity)
// ========
// Assume [sequences] is variable of type [Entities.Application]
string xmlString;
var xs = new XmlSerializer(typeof(Entities.Application));
using (var sw = new StringWriter())
{
xs.Serialize(sw, sequences);
xmlString = sw.ToString();
}
string encoded = System.Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(xmlString));
// Converting encoded [Entities.Application] to decoded XML string,
// using some of your code for consistency.
string encoded;
using (TextReader textReader = new StreamReader(XMLFile))
{
encoded = textReader.ReadToEnd();
textReader.Close();
}
string decoded = System.Text.Encoding.UTF8.GetString(
System.Convert.FromBase64String(encoded));
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Entities.Application));
using (var sr = new StringReader(decoded))
{
sequences = (Entities.Application)xmlSerializer.Deserialize(sr);
}
// Inserting Base64 in XmlElement
// ========
// Optional: the old MSXML.DOMDocument had nodeTypedValue, and you
// can set the same attributes if you are going to use DOMDocument, although
// it is still a good idea to tag the element so you know its datatype.
node.SetAttribute("xmlns:dt", "urn:schemas-microsoft-com:datatypes");
node.SetAttribute("dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
// Assume serialized data has already been encoded as shown above
var elem = node.AppendChild(xmlDoc.CreateTextNode(encoded));