How to implement Xml Serialization with inherited classes in C#

后端 未结 2 1390
无人及你
无人及你 2020-12-18 21:21

I have two classes : base class name Component and inheritd class named DBComponent

[Serializable]
public class Component
{
    private string name = strin         


        
相关标签:
2条回答
  • 2020-12-18 22:10

    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: Component
    public class ComponentDerivedClass2: Component
    public 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).

    0 讨论(0)
  • 2020-12-18 22:11

    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].

    0 讨论(0)
提交回复
热议问题