序列化List包含XML接口

我一直在读书,但我没有找到解决问题的办法

我目前正在使用一个业务对象来保存我的所有数据,我们需要将此对象转换为XML或从XML转换。

我的对象包含一系列动作(列表…),但有两种动作类型(目前为止)。 我必须操作类型SimpleAction和CompositeAction,它们都从IActioninheritance,允许它们都保存在Actions列表中。

现在您可能会看到问题,因为接口无法序列化,因为它们没有数据。

如何,通过一些示例代码,我是否可以编写获取该对象类型的Class或Serializer,然后使用正确的类型序列化对象?

一些代码:

[XmlArray("Actions")] public List Actions { get; set; } public interface IAction { int ID { get; set; } ParameterCollection Parameters { get; set; } List Validation { get; set; } TestResultEntity Result { get; set; } string Exception { get; set; } } [XmlType("A")] public class SimpleActionEntity : IAction { #region IAction Members [XmlAttribute("ID")] public int ID { get; set; } [XmlIgnore] public ParameterCollection Parameters { get; set; } [XmlIgnore] public List Validation { get; set; } [XmlIgnore] public TestResultEntity Result { get; set; } [XmlElement("Exception")] public string Exception { get; set; } #endregion } 

任何帮助将不胜感激。 🙂

你可以使用XmlArrayItemAttribute,正如我们所讨论的那样创建一个IAction列表是没有用的,所以创建基类是好的

 public interface IAction {} public abstract class ActionBase : IAction {} public class SimpleAction : ActionBase {} public class ComplexAction : ActionBase {} [XmlArray("Actions")] [XmlArrayItem(typeof(SimpleAction)),XmlArrayItem(typeof(ComplexAction))] public List Actions { get; set; } 

实际上你也可以在xml文件中控制元素名称,如下所示:

  [XmlArray("Actions")] [XmlArrayItem(typeof(SimpleAction),ElementName = "A")] [XmlArrayItem(typeof(ComplexAction),ElementName = "B")] public List Actions { get; set; } 

好的,我已经创建了一个解决方案,我觉得我做得非常好。

我所做的不是坚持

  [XmlArray("Actions")] public List Actions { get; set; } 

我决定创建一个处理List BUT的ActionCollection类,也允许我使用IXMLSerializable来覆盖ReadXml和WriteXML方法,以便我可以处理列表序列化和反序列化的方式。

 [XmlElement("Actions")] public ActionCollection Actions { get; set; } public class ActionCollection: CollectionBase, IXmlSerializable { #region IList Members ... #endregion #region ICollection Members ... #endregion #region IEnumerable Members ... #endregion #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { //TODO } public void WriteXml(System.Xml.XmlWriter writer) { foreach (IAction oAction in List) { XmlSerializer s = new XmlSerializer(oAction.GetType()); s.Serialize(writer, oAction); } } #endregion } 

也许你从一个实现接口的公共抽象基类派生你的两个动作类?

 public interface IAction {} public abstract class ActionBase : IAction {} public class SimpleAction : ActionBase {} public class ComplexAction : ActionBase {} 

然后使用List而不是使用List List