Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize random/unknown types with XmlSerializer [duplicate]

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 ?

like image 356
Oyvind Avatar asked Nov 21 '11 10:11

Oyvind


2 Answers

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

like image 141
L.B Avatar answered Sep 18 '22 13:09

L.B


As you mentioned when you request for the service might return . So do you know if an request is made for a type then the service might return only certain types back?

I would have tried XmlSerializer Constructor (Type, Type[])... Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.

like image 29
Amit Rai Sharma Avatar answered Sep 21 '22 13:09

Amit Rai Sharma