XmlSerializer抛出System.InvalidOperationException

时间:2016-07-29 12:31:57

标签: c# .net xml-serialization xmlserializer ixmlserializable

基本上我有两个班级:

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>

但是这段代码抛出了一个异常:类型&#39; System.InvalidOperationException&#39;的未处理异常。发生在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 : 以root身份对Section进行序列化/反序列化很有效

1 个答案:

答案 0 :(得分:2)

这是因为在类Section中进行反序列化时,读取器不会移动到下一个节点,并且会反复尝试读取同一节点,最终导致OutofMemory异常。读取属性后,应将读者指向下一个节点。可能还有其他方法可以解决此问题,但这应该可以解决您的问题。

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