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 : ルートとしてのセクションのシリアル化/逆シリアル化はうまく機能します

4

1 に答える 1

2

これは、クラスでデシリアライズ中にリーダーが次のノードに移動せずSection、同じノードの読み取りを繰り返し試行し、最終的に OutofMemory 例外が発生するためです。属性を読み取った後、リーダーを次のノードに向ける必要があります。この問題を解決する他の方法があるかもしれませんが、現時点ではこれで問題が解決するはずです。

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