我只是想使用 .NET 框架(2.0 版)的 XML-Serializer。我创建了对我的设置进行序列化和反序列化的方法:
public static void Save(string filename)
{
var settings = Settings.Instance;
if (File.Exists(filename))
File.Delete(filename);
using (var stream = File.OpenWrite(filename))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
serializer.Serialize(stream, settings);
}
}
Save-methods 工作得很好,因此我得到了以下 xml 文档:
<?xml version="1.0"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EnableHooking>true</EnableHooking>
<IncludePressedKeys>false</IncludePressedKeys>
<EnableFastScroll>false</EnableFastScroll>
<FastScrollingHotKeys>
<VirtualKeys>Control</VirtualKeys>
<VirtualKeys>Alt</VirtualKeys>
</FastScrollingHotKeys>
<ScrollSpeed>2</ScrollSpeed>
<FastScrollSpeed>10</FastScrollSpeed>
</Settings>
如果我尝试反序列化此文档,我会收到一个异常 XmlException,它告诉我缺少根元素。我尝试设置 XmlRootAttribute,尝试检查文件名和流位置。一切都好。现在我终于尝试通过完美运行的 XmlDocument 类读取加载文件。现在我真的不知道会发生什么。所以你可以看看Load-method:
public static void Load(string filename)
{
if (!File.Exists(filename))
throw new ArgumentException("File not found.", "filename", new FileNotFoundException());
//works
var doc = new XmlDocument();
doc.Load(XmlReader.Create(File.OpenRead(filename)));
Console.WriteLine(doc.DocumentElement.FirstChild);
using (var stream = File.OpenRead(filename))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
_instance = serializer.Deserialize(stream) as Settings;
}
}
希望有人有想法。