我想将以下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