我只是想使用.NET框架的XML-Serializer(版本2.0)。 我创建了方法来序列化和反序列化我的设置:
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;
}
}
希望有人有个主意。
答案 0 :(得分:1)
当我使用Xamarin Studio在OSX上使用以下代码(我在其中添加了一个简单版本的Settings类)时,我没有错误。
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Test
{
class MainClass
{
private static Settings _instance;
public static void Main (string[] args)
{
Load ("Settings.xml");
}
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;
}
}
}
public class Settings
{
public bool EnableHooking {
get;
set;
}
public bool IncludePressedKeys {
get;
set;
}
}
}
当我检查_instance的值时,属性被设置为正确的值。我在第二个属性之后删除了XML。问题可能在于更“复杂”的XmlElement“FastScrollingHotKeys”。你可以发布你的设置课吗?