DataContractSerializer 读取会导致“缺少带有编码的 XML 声明”,知道为什么吗?

问题描述 投票:0回答:1

我使用

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. 
}
c# xml datacontractserializer
1个回答
0
投票

异常原因是少了一行

<?xml version="1.0" encoding="utf-8"?>

如上所述,有两种解决方案:

  1. 使用
    XmlWriter
    创建线条:
    using (XmlWriter writer = XmlWriter.Create(fn, settings))
  2. 使用
    XmlTextWriter
    并添加
    writer.WriteStartDocument();

感谢以上所有提供帮助的人。

© www.soinside.com 2019 - 2024. All rights reserved.