C# – XmlSerializer construction with same named extra types

cnetxml-serialization

Hey, I am hitting trouble constructing an XmlSerializer where the extra types contains types with the same Name (but unique Fullname). Below is an example that illustrated my scenario.

Type definitions in external assembly I cannot manipulate:

public static class Wheel
{
  public enum Status { Stopped, Spinning }
}

public static class Engine
{
  public enum Status { Idle, Full }
}

Class I have written and have control over:

public class Car
{
  public Wheel.Status WheelStatus;
  public Engine.Status EngineStatus;

  public static string Serialize(Car car)
  {
    var xs = new XmlSerializer(typeof(Car), new[] {typeof(Wheel.Status),typeof(Engine.Status)});

    var output = new StringBuilder();
    using (var sw = new StringWriter(output))
      xs.Serialize(sw, car);

    return output.ToString();
  }
}

The XmlSerializer constructor throws a System.InvalidOperationException with Message

"There was an error reflecting type 'Engine.Status'"

This exception has an InnerException of type System.InvalidOperationException and with Message

"Types 'Wheel.Status' and 'Engine.Status' both use the XML type name, 'Status', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type."

Given that I am unable to alter the enum types, how can I construct an XmlSerializer that will serialize Car successfully?

Best Answer

The first thing I notice is that Car.Status does not exist. Do you mean Engine.Status?

In any case, if those enum types were designed in such a way that they cannot be serialized automatically, you will have to serialize them manually.

Related Topic