views:

184

answers:

3

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?

A: 

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.

Charlie Salts
A: 

you can serialize it by implementing IXmlSerializable Interface on each of the class, then you will get 3 methods

GetSchema()
ReadXml()
WriteXml()

in GetSchema method simply put return null; and in WriteXml() method put the code you need to write the xml while serializing the object, and in ReadXml() method put the code you need to Read ffrom xml file and recreating the object while deserializing.

viky
A: 

Try using the XmlElement attribute:

public class Car
{
    [XmlElement("WheelStatus")]
    public Wheel.Status WheelStatus;
    [XmlElement("EngineStatus")]
    public Engine.Status EngineStatus;

    ...

}

UPDATE: Just tried this, and it doesn't seem to work in this case.

Chris Dunaway