Want to serialize my data in this:
<?xml version="1.0" encoding="ibm850"?> <Batch Name="Test batch"> <ExecuteCommand Command="..." /> <WaitCommand Seconds="5" /> </Batch>
But instead, I get this (note the wrapping command element)
<?xml version="1.0" encoding="ibm850"?> <Batch Name="Test batch"> <Commands> <ExecuteCommand Command="..." /> <WaitCommand Seconds="5" /> </Commands> </Batch>
Here is a sample code used to create this:
public class BaseCommand //base class { [XmlAttribute] public string Result { get; set; } } public class ExecuteCommand : BaseCommand { [XmlAttribute] public string Command { get; set; } } public class WaitCommand : BaseCommand { [XmlAttribute] public int Seconds { get; set; } } public class Batch { [XmlAttribute] public string Name { get; set; } private List<BaseCommand> _commands = new List<BaseCommand>(); [XmlArrayItem(typeof(ExecuteCommand))] [XmlArrayItem(typeof(WaitCommand))] public List<BaseCommand> Commands { get { return _commands; } set { _commands = value; } } public static void Main() { XmlSerializer serializer = new XmlSerializer(typeof(Batch)); Batch b = new Batch(); b.Name = "Test batch"; b.Commands.Add(new ExecuteCommand() { Command = "..." }); b.Commands.Add(new WaitCommand() { Seconds = 5 }); serializer.Serialize(Console.Out, b); Console.Read(); } }
I searched and read heaps of articles on this topic. They seem to provide a solution for serializing collections with one type of class (without inheritance). I use inheritance and nothing works. Unfortunately, I have to output the exact XML document due to old support
kaalen
source share