2009-10-29 11 views
16

XMLSerializerを使ってジェネリックリストを含むオブジェクトを直列化しています。XmlSerializerを使用して派生クラスをシリアル化する

List <ChildBase> Children {get;set}

問題は各要素が実際には抽象クラスであるChildBaseから派生していることです。 デシリアライズしようとすると、invalidOperationExceptionが発生する

派生オブジェクトでXMLSerializerを使用する方法はありますか?ありがとう。

答えて

39

これには3つの方法があります。タイプに対して[XmlInclude]を使用するか、XmlElement/XmlArrayItemをプロパティに対して使用することができます。それらはすべて下に示されています。あなたが好きなペアのコメントを外してください:

using System; 
using System.Collections.Generic; 
using System.Xml.Serialization; 
public class MyWrapper { 
    //2: [XmlElement("A", Type = typeof(ChildA))] 
    //2: [XmlElement("B", Type = typeof(ChildB))] 
    //3: [XmlArrayItem("A", Type = typeof(ChildA))] 
    //3: [XmlArrayItem("B", Type = typeof(ChildB))] 
    public List<ChildClass> Data { get; set; } 
} 
//1: [XmlInclude(typeof(ChildA))] 
//1: [XmlInclude(typeof(ChildB))] 
public abstract class ChildClass { 
    public string ChildProp { get; set; } 
} 
public class ChildA : ChildClass { 
    public string AProp { get; set; } 
} 
public class ChildB : ChildClass { 
    public string BProp { get; set; } 
} 
static class Program { 
    static void Main() { 
     var ser = new XmlSerializer(typeof(MyWrapper)); 
     var obj = new MyWrapper { 
      Data = new List<ChildClass> { 
       new ChildA { ChildProp = "abc", AProp = "def"}, 
       new ChildB { ChildProp = "ghi", BProp = "jkl"}} 
     }; 
     ser.Serialize(Console.Out, obj); 
    } 
} 
+0

そして、これを適用しようとする:[XmlRoot(ElementName = "myWrapper"、Namespace = "http:// URL /")] public class MyWrapper –

+0

ありがとう!このことを理解しようとすると、私の頭をレンガの壁にぶつけていた。 – iagomartinez

+0

何か偉大な答え – sjclark76

5

これにはXmlIncludeAttributeを使用できます。またはこれを行う別の方法でthis投稿を参照してください。

+0

[このリンクがありません] –

+0

ありがとうございます。修正されました。 –

+1

それはそれをしました。ありがとう。 –

関連する問題