我使用
DataContractSerializer
将记录写入 XML 文件。工作没有问题。但当我回读时,我遇到了一个例外:Loading snapshot failed, An XML declaration with an encoding is required for all non-UTF8 documents
。
有什么想法吗?或者更好的是,我可以配置
XmlTextWriter
来写入该编码信息吗?
写作:
DataContractSerializer serializer = new(typeof(RMonitorSnapshot));
using (XmlTextWriter writer = new(fn, Encoding.Unicode))
{
writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable
serializer.WriteObject(writer, snapshot);
writer.Flush();
}
阅读:
RMonitorSnapshot? snapshot = null;
DataContractSerializer serializer = new(typeof(RMonitorSnapshot));
try {
using (FileStream fs = File.Open(fn, FileMode.Open)) {
snapshot = serializer.ReadObject(fs) as RMonitorSnapshot;
}
}
catch (Exception ex) {
... Loading snapshot failed, An XML declaration with an encoding is required for all non-UTF8 documents.
}
异常原因是少了一行
<?xml version="1.0" encoding="utf-8"?>
如上所述,有两种解决方案:
XmlWriter
创建线条:using (XmlWriter writer = XmlWriter.Create(fn, settings))
XmlTextWriter
并添加 writer.WriteStartDocument();
感谢以上所有提供帮助的人。