如何使用C#中的inheritance类实现Xml序列化

我有两个类:基类名称Component和名为DBComponent的inheritance类

[Serializable] public class Component { private string name = string.Empty; private string description = string.Empty; } [Serializable] public class DBComponent : Component { private List spFiles = new List(); // Storage Procedure Files [XmlArrayItem("SPFile", typeof(string))] [XmlArray("SPFiles")] public List SPFiles { get { return spFiles; } set { spFiles = value; } } public DBComponent(string name, string description) : base(name, description) { } } [Serializable] public class ComponentsCollection { private static ComponentsCollection instance = null; private List components = new List(); public List Components { get { return components; } set { components = value; } } public static ComponentsCollection GetInstance() { if (ccuInstance == null) { lock (lockObject) { if (instance == null) PopulateComponents(); } } return instance; } private static void PopulateComponents() { instance = new CCUniverse(); XmlSerializer xs = new XmlSerializer(instance.GetType()); instance = xs.Deserialize(XmlReader.Create("Components.xml")) as ComponentsCollection; } } 

}

我想从Xml文件读取\ write。 我知道我需要为DBComponent类实现Serialization,否则它将无法读取它。但是我找不到任何简单的文章。 我发现的所有文章对于这个简单的场景来说太复杂了。
Xml文件如下所示:

      Setup\TenantHistoricalSP.sql      

有人可以给我一个简单的例子,说明如何阅读这种xml文件以及应该实现什么?

谢谢
利奥尔

不幸的是,您需要使用XmlArrayItem()属性告诉XmlSerializer您要序列化或反序列化的类。 每种不同的类型也需要自己的元素名称。 例如:

 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 Components { // ... } } 

这将读取一个XML文件,如:

               

可以存在每个元素的多个实例(或者不存在)。

不同scenrios的两个选项:告诉基类

 [XmlInclude(typeof(DBComponent))] public class Component { private string name = string.Empty; private string description = string.Empty; } 

或者:告诉collections:

 [XmlArray] [XmlArrayItem("Component", typeof(Component))] [XmlArrayItem("DBComponent", typeof(DBComponent))] public List Components {...} 

实际上,如果不需要外部节点(Components),也可以使用[XmlElement(…)]代替[XmlArrayItem]。 另外:您不需要[Serializable]。

所以,就我从代码中看到的那样,你已经实现了类序列化了吗? 如果您尝试从XML文件中取回对象,请使用反序列化器:

System.Xml.Serialization.XmlSerializer.Deserialize

如果不是,请记住您始终可以从XML Schema生成代码