Deserialize random/unknown types with XmlSerializer

Oyvind picture Oyvind · Nov 21, 2011 · Viewed 13.3k times · Source

I am using XmlSerializer to communicate with a service. This is not a regular SOAP service, it has its own XML object types. For example, I may ask for a <Capabilities> object, but it may return an <Exception>. So, in other words, I have to deal with random XML document types. I do however, know which types I have to deal with.

What I am trying to do is to find a generic approach to serialize/deserialize these documents. The problem is that the XmlSerializer needs to know the type at creation stage.

These are NOT encapsulated in a common root element, so making a base class and using the [XmlInclude] attribute does NOT work in this case:

[XmlInclude(typeof(Exception))]
[XmlInclude(typeof(Capabilities))]
public abstract class BaseClass
{
  public BaseClass()
  {
    SchemaLocation = "test";
  }

  [XmlAttribute("schemaLocation")]
  public String SchemaLocation { get; set; }
}

[XmlRoot("Exception")]
public class Exception : BaseClass
{
  public Exception():base()
  {
  }
  [XmlElement]
  public String Message { set; get; }
}

[XmlRoot("Capabilities")]
public class Capabilities : BaseClass
{
  public Capabilities() : base()
  {}
  [XmlElement]
  public String ServiceName { set; get; }
}

My solution so far is to probe the root element manually with the XmlReader, and then map it to the correct type before creating an XmlSerializer instance.

Is there any better way of doing this ?

Answer

L.B picture L.B · Nov 21, 2011

I don't know whether it is better or not but you may try DynamicObject approach. http://blogs.msdn.com/b/csharpfaq/archive/2009/10/19/dynamic-in-c-4-0-creating-wrappers-with-dynamicobject.aspx