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

发布于 2024-09-12 17:36:03 字数 1179 浏览 2 评论 0原文

这是我正在使用的代码。我不断收到 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());

Here's the code I'm using. I keep getting xml document errors

[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;
    }
}

And here's the code to actually serialize

    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());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若言繁花未落 2024-09-19 17:36:03

It looks like this might be your answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文