0

我只是想使用 .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;
    }
}

希望有人有想法。

4

1 回答 1

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”中。你能发布你的设置类吗?

于 2013-07-20T19:00:14.750 回答