I want to deserialize/serialize the following XML into an object.
<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>
Is it possible to have the @Type attribute define what type of object should be used to serialize?
For example, in C#:
[XmlArray]
[XmlArrayItem("Discount",typeof(Voucher)]
[XmlArrayItem("Discount",typeof(Quantity)]
public List<Discount> Discounts { get; set; }
I hope my explanation makes sense. Any help would be appreciated. Thanks.
Update after Andrew Anderson answer:
Here is the updated 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>
I changed the my classes to look like this:
[Serializable]
[XmlInclude(typeof(Voucher))]
[XmlInclude(typeof(Quantity))]
[XmlRoot("Discount")]
public class Discount
{ ... }
public class Quantity : Discount { }
public class Voucher : Discount { }
When I deserialize this, the 'Discounts' list has two 'Discount' objects. I would expect at this point that the list should have a 'Quantity' object and 'Voucher' object. This could be because the my list is defined to have only a 'Discount' object. Following is the code for my 'Discounts' list object.
[XmlArray]
[XmlArrayItem("Discount")]
public List<Discount> Discounts { get; set; }
The question now is how can I setup the list to contain the two different types of objects?