I have a class which represents a bunch of settings:
public class Settings
{
public Settings()
{
InnerSettings = new List<InnerSettings>();
//this is the settings i want to have by default
InnerSettings.Add(new InnerSettings());
}
[XmlArray]
public List<InnerSettings> InnerSettings {get; set;}
}
Now, when I deserialize this object, the InnerSettings from XML are added to the List on top of the items which were created in default Settings() constructor. Is there an easy way to tell deserializer, that I want to overwrite the collection instead, removing the default items?
XML Serializer doesn't support any callback and deriving from
XmlSerializerclass there are few methods you can override. Let's see some (dirty) workarounds:1) Change default constructor (the one
XmlSerializerwill call) to do not include default item(s). Add a second constructor with a dummy parameter and expose a factory method:2) Remove items after object has been deserialized. Create your own
XmlSerializerfor this:3) It should be right way to do it but it's not easy for complex types: the long job of
IXmlSerializableimplementation...