I'm working with an externally developed XSD that I need to conform to, where a field Engine can be one of two types: Electric or Combustion. Both are derived from super-class Engine.
There are multiple ways to have the XmlSerializer in C# handle this, but all are seemingly associated with the same side-effect: default serialization naming conventions are tossed out the window when using a custom serializer-apporach. I want to mimic the default behaviour for the remaining fields of the class Vehicle.
Consider the following:
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace DMV
{
public class Vehicle : IXmlSerializable
{
public Engine Engine { get; set; }
[XmlElement("Manufacturer")]
public Company Manufacturer { get; set; }
public void WriteXml(XmlWriter writer)
{
XmlSerializer engineSerializer = new XmlSerializer(Engine.GetType());
engineSerializer.Serialize(writer, Engine);
XmlSerializer manufacturerSerializer = new XmlSerializer(Manufacturer.GetType());
manufacturerSerializer.Serialize(writer, Manufacturer);
}
}
public abstract class Engine { }
public class Electric : Engine
{
public int Poles { get; set; }
}
public class Combustion : Engine
{
public int CC { get; set; }
}
public class Company
{
public string Name { get; set; }
}
}
I try to run this using following serialization code:
Vehicle vehicle = new Vehicle();
vehicle.Engine = new Electric();
vehicle.Manufacturer = new Company();
XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, vehicle);
Console.WriteLine(writer.ToString());
writer.Close();
The result is the following dissapointing pile of caballus faeces:
<Vehicle>
<Electric>
<Poles>0</Poles>
</Electric>
<Company/>
</Vehicle>
(Yes, the Engine field is serialized properly, but Company not so much.)
If I had used the default (built-in) serialization I would've gotten the following (desired!) output:
<Vehicle>
<Manufacturer />
</Vehicle>
How can I both serialize the derived classes Electric or Combustion, while retaining the default naming convention for field Manufacturer (of type Company)?