I have an array of Fruit objects, some of them Oranges, some of them Apples.
I would like to serialize them to a list that looks like:
<Fruits>
<AppleFruit>
<IsRotten>true</IsRotten>
<FellFarFromTree>false</FellFarFromTree>
</AppleFruit>
<OrangeFruit>
<IsRotten>false</IsRotten>
<NumberOfSegments>6</NumberOfSegments>
</OrangeFruit>
</Fruits>
So I'm trying the following:
[Serializable]
[XmlInclude(typeof(Apple))]
[XmlInclude(typeof(Orange))]
public abstract class Fruit {
public bool IsRotten { get; set; }
}
[Serializable]
[XmlRoot("AppleFruit")]
public class Apple : Fruit {
public bool FellFarFromTree { get; set; }
}
[Serializable]
[XmlRoot("OrangeFruit")]
public class Orange : Fruit {
public int NumberOfSegments { get; set; }
}
public class Blender {
public void XmlBlend(params Fruit[] fruits) {
using (var writer = new XmlTextWriter(@"c:\test\blended_fruits.xml", Encoding.UTF8)) {
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Fruits");
var serializer = new XmlSerializer(typeof (Fruit));
foreach (var fruit in fruits) {
serializer.Serialize(writer, fruit);
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
[Test]
public void TestIt () {
var blender = new Blender();
blender.XmlBlend(
new Apple() {
FellFarFromTree = false,
IsRotten = true
},
new Orange() {
IsRotten = false,
NumberOfSegments = 6
});
}
}
But the XmlRoot attribute seems to be totally ignored. The actual output comes out looking like:
<Fruits>
<Fruit xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Apple">
<IsRotten>true</IsRotten>
<FellFarFromTree>false</FellFarFromTree>
</Fruit>
<Fruit xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Orange">
<IsRotten>false</IsRotten>
<NumberOfSegments>6</NumberOfSegments>
</Fruit>
</Fruits>
What am I missing?