2012-02-12 6 views
6

抽象基本クラスを使用して汎用オブジェクトのリストをシリアライズする方法に関する良いサンプルです。非抽象基本クラスのサンプルはXML Serialize generic list of serializable objectsにリストされています。基本クラスはMicrosoft.Build.Utilities.TaskXML抽象基本クラスを持つシリアライズ可能オブジェクトの汎用リストをシリアル化します。

+0

@ドミトリーと同意します。あなたがXmlArrayItemAttributeを代わりに使うことができるAnimals要素を保つことができないなら、代わりの答えはXmlIncludeを使わないシリアライズhttp://stackoverflow.com/questions/370291/serializing-without-xmlinclude – walter

答えて

4

と似ています。厳密な型指定リストなどを使用できるように、いくつかの派生型を持つ抽象クラスを持つと便利なことがよくあります。

たとえば、抽象クラスであるDocumentFragmentクラスと、TextDocumentFragmentおよびCommentDocumentFragmentという2つの具象クラス(Willisのこの例)があります。

これにより、2つのタイプのオブジェクトのみを含むListプロパティを作成することができます。

あなたはXmlInclude属性は、それがかもしれないというクラスを教えて

[Serializable()] 
[System.Xml.Serialization.XmlInclude(typeof(TextDocumentFragment))] 
[System.Xml.Serialization.XmlInclude(typeof(CommentDocumentFragment))] 
public abstract class DocumentFragment { 
...} 

....あなたがエラーを取得するが、これは以下のコードで周りを取得するのは簡単です、このリストを返すWebサービスを作成しようとするとそれらの2つの派生クラスにシリアル化されます。

これは、以下のように実際のタイプを指定する属性をDocumentFragmentエレメントに生成します。

このメソッドを使用すると、派生クラスに固有の任意の追加プロパティも含まれます。

11

別の方法としては、醜いなし(...ジェネリックリスト自体に知られているタイプのリストを移動するためにXmlElementAttributeを使用することも、より良い探してXML出力になります

using System; 
using System.Xml; 
using System.Xml.Serialization; 
using System.Collections.Generic; 

public abstract class Animal 
{ 
    public int Weight { get; set; }  
} 

public class Cat : Animal 
{ 
    public int FurLength { get; set; }  
} 

public class Fish : Animal 
{ 
    public int ScalesCount { get; set; }  
} 

public class AnimalFarm 
{ 
    [XmlElement(typeof(Cat))] 
    [XmlElement(typeof(Fish))] 
    public List<Animal> Animals { get; set; } 

    public AnimalFarm() 
    { 
     Animals = new List<Animal>(); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     AnimalFarm animalFarm = new AnimalFarm(); 
     animalFarm.Animals.Add(new Cat() { Weight = 4000, FurLength = 3 }); 
     animalFarm.Animals.Add(new Fish() { Weight = 200, ScalesCount = 99 }); 
     XmlSerializer serializer = new XmlSerializer(typeof(AnimalFarm)); 
     serializer.Serialize(Console.Out, animalFarm); 
    } 
} 

...ですxsi:type属性)...

<?xml version="1.0" encoding="ibm850"?> 
<AnimalFarm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Cat> 
    <Weight>4000</Weight> 
    <FurLength>3</FurLength> 
    </Cat> 
    <Fish> 
    <Weight>200</Weight> 
    <ScalesCount>99</ScalesCount> 
    </Fish> 
</AnimalFarm> 
+0

で見つけることができます。 – Console

関連する問題