How to XML serialize polymorphic array without wrapping element

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><!-- I want to get rid of thiw wrapper Commands element and just --> <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

+7
source share
1 answer

It was a long time ago, but in the end I realized it myself.

The solution was to add the [XmlElement] attribute for each of the supported derived types to the collection property

 private List<BaseCommand> _commands = new List<BaseCommand>(); [XmlElement(typeof(ExecuteCommand))] [XmlElement(typeof(WaitCommand))] public List<BaseCommand> Commands { get { return _commands; } set { _commands = value; } } 
+8
source

All Articles