XmlSerializer 抛出 System.InvalidOperationException

XmlSerializer throws System.InvalidOperationException

所以基本上我有 2 类:

public class Configuration
{
    public Configuration()
    {
        Sections = new List<Section>();
    }

    public List<Section> Sections { get; private set; }
}

public class Section : IXmlSerializable
{
    public string Name { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        Name = reader.GetAttribute("Name");
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("Name", Name);
    }
}

此代码运行良好:

var configuration = new Configuration();
configuration.Sections.Add(new Section {Name = "#Submitter.LoginTest"});
configuration.Sections.Add(new Section {Name = "Default"});

using (StreamWriter writer = new StreamWriter(@"d:\data.xml"))
{
    XmlSerializer x = new XmlSerializer(typeof(Configuration));
    x.Serialize(writer, configuration, XmlSerializerHelper.EmptyNamespaces);
}

序列化结果:

<?xml version="1.0" encoding="utf-8"?>
<Configuration>
  <Sections>
    <Section Name="#Submitter.LoginTest" />
    <Section Name="Default" />
  </Sections>
</Configuration>

但是此代码抛出异常:'System.InvalidOperationException' 类型的未处理异常发生在 System.Xml.dll 附加信息:XML 文档 (4, 6) 中存在错误。

var configuration = new Configuration();
using (StreamReader reader = new StreamReader(@"d:\data.xml"))
{
    XmlSerializer x = new XmlSerializer(typeof(Configuration));
    configuration = (Configuration) x.Deserialize(reader);
}

所以对于第 I 部分的序列化不能使用基于属性的序列化,但它工作得很好:

public class Section
{    
    [XmlAttribute]
    public string Name { get; set; }
}

UPD1: Serialization/deserialization 的部分作为根效果很好

是因为reader在classSection中反序列化时没有移动到下一个节点,反复尝试读取同一个节点最终导致OutofMemory异常。读取属性后,您应该将 reader 指向下一个节点。可能有其他方法可以解决此问题,但这应该可以解决您目前的问题。

public void ReadXml(XmlReader reader)
{
    Name = reader.GetAttribute("Name");
    reader.Read();
}