My goal is to serialize a collection of type IList<AbstractClass> which contains derived objects instances.
My domain object model is a bit complex so I've created a demmi one:
Expand|Select|Wrap|Line Numbers
- public abstract class ProductBase
- {
- protected int _id;
- public int ID
- {
- get { return _id; }
- set { _id = value; }
- }
- protected string _name;
- public string Name
- {
- get { return _name; }
- set { _name = value; }
- }
- }
- public class Coffee : ProductBase
- {
- private string _type;
- public string Type
- {
- get { return _type; }
- set { _type = value; }
- }
- private bool _isDecaff;
- public bool IsDecaff
- {
- get { return _isDecaff; }
- set { _isDecaff = value; }
- }
- }
- public class Tea : ProductBase
- {
- private int _numOfSachets;
- public int NumOfSachets
- {
- get { return _numOfSachets; }
- set { _numOfSachets = value; }
- }
- }
- public class Store
- {
- private List<ProductBase> _products = new List<ProductBase>();
- public List<ProductBase> Products
- {
- get { return _products; }
- set { _products = value; }
- }
- }
Expand|Select|Wrap|Line Numbers
- static void Main(string[] args)
- {
- Store store = new Store();
- Coffee prod1 = new Coffee();
- prod1.Type = "Espresso";
- Tea prod2 = new Tea();
- prod1.NumOfSachets = 50;
- store.Products.Add(prod1);
- store.Products.Add(prod2);
- //TODO: Represent store as XML document
- }
<Store>
<Products></Store><Coffee type="Espresso" /><Tea NumOfSachets="50" /></Products>
So far I've done serialization using the XmlSerializer but I can't seem to get it working in here. I've decorated all the attributes and elements of the base and derived classes, but the serialization fails until i add a
Expand|Select|Wrap|Line Numbers
- [XmlInclude(typeof(Coffee))]
Can someone please explain how it's suppose to be done?
Tnx in advance,
Shaul