How to implement Xml Serialization with inherited classes in C#
Unfortunately, you need to tell the XmlSerializer
the classes you intend to serialize or deserialize using the XmlArrayItem()
attribute. Each different type also needs its own element name. For example:
public class ComponentDerviedClass1: Componentpublic class ComponentDerivedClass2: Componentpublic class ComponentDerivedClass3: Component// ...public class ComponentsCollection{ [XmlArray("Components")] [XmlArrayItem("ComponentDerivedClass1", typeof(ComponentDerivedClass1))] [XmlArrayItem("ComponentDerivedClass2", typeof(ComponentDerivedClass2))] [XmlArrayItem("ComponentDerivedClass3", typeof(ComponentDerivedClass3))] public List<Component> Components { // ... }}
This would read an XML file like:
<?xml version="1.0" encoding="utf-8" ?><ComponentsCollection> <Components> <ComponentDerivedClass1> <!-- ... --> </ComponentDerivedClass1> <ComponentDerivedClass2> <!-- ... --> </ComponentDerivedClass2> <ComponentDerivedClass3> <!-- ... --> </ComponentDerivedClass3> </Components> </ComponentsCollection>
Multiple instances of each element can be present (or none).
Two options for different scenrios: tell the base-class
[XmlInclude(typeof(DBComponent))]public class Component{ private string name = string.Empty; private string description = string.Empty; }
Or: tell the collection:
[XmlArray][XmlArrayItem("Component", typeof(Component))][XmlArrayItem("DBComponent", typeof(DBComponent))]public List<Component> Components {...}
Actually, you can also use [XmlElement(...)] in place of [XmlArrayItem] if you don't want the outer node (Components). Also: you don't need [Serializable].