2010-08-04 41 views
0

這是我使用的代碼。我不斷收到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()); 

回答

0

看起來this可能是你的答案代碼。

+0

該示例沒有顯示多個不同的被序列化的繼承類。他只有1個類,並正在序列化該類的數組 – Tom 2010-08-05 14:10:23

相關問題