序列化List包含XML接口

时间:2009-07-15 14:18:45

标签: c# xml serialization

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

我目前正在处理一个包含所有数据的业务对象,我们需要将此对象转换为XML格式。

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

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

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

一些代码:

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

  public interface IAction
   {
     int ID { get; set; }

     ParameterCollection Parameters { get; set; }

     List<SectionEntity> 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<SectionEntity> Validation { get; set; }

    [XmlIgnore]
    public TestResultEntity Result { get; set; }

    [XmlElement("Exception")]
    public string Exception { get; set; }

    #endregion
}

非常感谢任何帮助。 :)

3 个答案:

答案 0 :(得分:4)

你可以使用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<ActionBase> Actions { get; set; }

实际上你也可以像这样控制xml文件中的元素名称:

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

答案 1 :(得分:2)

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

我所做的不是举行

 [XmlArray("Actions")]
 public List<IAction> 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
}

答案 2 :(得分:0)

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

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

然后使用List<IAction>

,而不是使用List<ActionBase>
相关问题