2016-07-29 12 views
0

だから基本的に私は2クラス持ってスロー:のXmlSerializerがSystem.InvalidOperationExceptionが

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:セクションの シリアライズ/デシリアライゼーションのルートがうまく機能として

答えて

2

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

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

ありがとうございました。 –

関連する問題