如何将具有相同基类的多个对象序列化为 xml?
这是我正在使用的代码。我不断收到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它看起来像这个 可能是你的答案。
It looks like this might be your answer.