如何将具有相同基类的多个对象序列化为xml?

时间:2010-08-04 20:41:17

标签: inheritance xml-serialization multiple-inheritance

这是我正在使用的代码。我一直在收到xml文档错误

[Serializable]
[XmlRoot("Command")]
public class Command
{
    [XmlElement("CommandType")]
    public CommandType CommandType { get; set; }
}

[Serializable]
[XmlRoot("DelayCommand")]
[XmlInclude(typeof(Command))]
public class DelayCommand : Command
{
    [XmlElement("Delay")]
    public int Delay { get; set; }

    public DelayCommand()
    {
        CommandType = CommandType.Delay;
    }
}

[Serializable]
[XmlRoot("HeartbeatCommand")]
[XmlInclude(typeof(Command))]
public class HeartbeatCommand : Command
{
    [XmlElement("HeartbeatOn")]
    public bool HeartbeatOn { get; set; }

    public HeartbeatCommand()
    {
        CommandType = CommandType.Heartbeat;
    }
}

这是实际序列化的代码

    FileStream Filewriter = new FileStream(path, FileMode.OpenOrCreate);

    XmlSerializer XmlFormat = new XmlSerializer(typeof(Command[])); // Make class as an array.

    List<Command> commands = new List<Command>();
    foreach (DataGridViewRow row in gridCommand.Rows)
    {
         commands.Add(row.Tag as Command);
    }

    XmlFormat.Serialize(Filewriter, commands.ToArray());

1 个答案:

答案 0 :(得分:0)

看起来this似乎是你的答案。