0

所以基本上我有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.Xml.dll 中发生类型为“System.InvalidOperationException”的未处理异常附加信息: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);
}

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

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

UPD1:Section 作为 root 的序列化/反序列化效果很好

4

1 回答 1

2

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

public void ReadXml(XmlReader reader)
{
    Name = reader.GetAttribute("Name");
    reader.Read();
}
于 2016-07-29T12:54:26.207 回答