The setup:
class Item { private int _value; public Item() { _value = 0; } public int Value { get { return _value; } set { _value = value; } } } class ItemCollection : Collection<Item> { private string _name; public ItemCollection() { _name = string.Empty; } public string Name { get {return _name;} set {_name = value;} } }
Now, trying to serialize using the following code fragment:
ItemCollection items = new ItemCollection(); ... XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection)); using (FileStream f = File.Create(fileName)) serializer.Serialize(f, items);
Upon looking at the resulting XML I see that the ItemCollection.Name value is not there!
I think what may be happening is that the serializer sees the ItemCollection type as a simple Collection thus ignoring any other added properties…
Is there anyone having encountered such a problem and found a solution?
Regards,
Stécy
This behavior is ‘By Design’. When deriving from a collection class the Xml Seralizier will only serialize the collection elements. To work around this you should create a class that encapsulates the collection and the name and have that serialized.
A detailed discussion is available here: http://blogs.vertigo.com/personal/chris/Blog/archive/2008/02/01/xml-serializing-a-derived-collection.aspx