我想將以下XML反序列化/序列化爲一個對象。如何用xml中的C#中的多個數據類型序列化列表?
<Discounts>
<Discount Type="Voucher" Key="ABCD00001" Percent="2" />
<Discount Type="Quantity">
<Periods>
<Period From="Thu, 31 Dec 2009 23:00:00 GMT" Quantity="1" />
<Period From="Thu, 31 Dec 2009 23:00:00 GMT" Quantity="2" />
</Periods>
</Discount>
</Discounts>
是否有可能讓@Type屬性定義應使用哪種類型的對象來序列化?
例如,在C#:
[XmlArray]
[XmlArrayItem("Discount",typeof(Voucher)]
[XmlArrayItem("Discount",typeof(Quantity)]
public List<Discount> Discounts { get; set; }
我希望我的解釋是有道理的。任何幫助,將不勝感激。謝謝。
後更新安德魯·安德森答案:
以下是更新XML:
<Discounts>
<Discount xsi:Type="Voucher" Key="ABCD00001" Percent="2" />
<Discount xsi:Type="Quantity">
<Periods>
<Period From="Thu, 31 Dec 2009 23:00:00 GMT" Quantity="1" />
<Period From="Thu, 31 Dec 2009 23:00:00 GMT" Quantity="2" />
</Periods>
</Discount>
</Discounts>
我改變我的類看起來就像這樣:
[Serializable]
[XmlInclude(typeof(Voucher))]
[XmlInclude(typeof(Quantity))]
[XmlRoot("Discount")]
public class Discount
{ ... }
public class Quantity : Discount { }
public class Voucher : Discount { }
當我反序列化這個,「折扣」列表有兩個「折扣」對象。我期望在這一點上,清單應該有一個'數量'對象和'憑證'對象。這可能是因爲我的列表被定義爲只有一個「折扣」對象。以下是我的「折扣」列表對象的代碼。
[XmlArray]
[XmlArrayItem("Discount")]
public List<Discount> Discounts { get; set; }
現在的問題是如何設置列表以包含兩種不同類型的對象?
另外,你對XML的外觀靈活,或者它必須是完全按照您所貼? – 2010-06-14 15:55:48
你負責格式嗎?如果是這樣,爲什麼不用XML中的「VoucherDiscount」和「QuantityDiscount」替換「Discount」? – Joseph 2010-06-14 15:59:32
當它出現時,對它使用樣式表似乎是最容易的,當它出來時,但我想避免改變任何東西。 – chafnan 2010-06-14 16:51:37