2

I'm trying to figure out how to serialize the following class into XML (in a specific way, see below):

[XmlRoot("Farm")]
public class Farm
{
    [XmlArray]
    [XmlArrayItem("Person", typeof(Person))]
    [XmlArrayItem("Dog", typeof(Dog))]
    public List<Animal> Animals { get; set; }
}

(Assume that Dog and Person both derive from Animal, and they both have a Name property which is decorated with [XmlAttribute("Name")].)

I need to be able to create this object:

var myFarm = new Farm
{
    Animals = new List<Animal> { 
        new Person { Name = "Bob" },  
        new Dog { Name = "Fido" }
    }
};

...and have it serialize to the following document:

<?xml version="1.0"?>
<Farm>
    <Person Name="Bob"/>
    <Dog Name="Fido"/>
</Farm>

But, when I serialize myFarm (result outputs to console) like this:

var serializer = new XmlSerializer(typeof(Farm));
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", "");
serializer.Serialize(System.Console.Out, myFarm, namespaces);

...the result is this:

<?xml version="1.0"?>
<Farm>
    <Animals>
        <Person Name="Bob"/>
        <Dog Name="Fido"/>
    </Animals>
</Farm>

Notice the extra unwanted Animals element. How do I get rid of this? Changing the XML schema is not an option, but changing the code is. I'd really just like to be able to get around this problem and am hoping someone knows of an easy fix (or knows for a fact that there is not an easy fix).

Thanks!

Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86

1 Answers1

3

Use the following attributes instead:

[XmlRoot("Farm")]
public class Farm
{
    [XmlElement("Person", typeof(Person))]
    [XmlElement("Dog", typeof(Dog))]
    public List<Animal> Items { get; set; }
}
Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56