15

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 ?

Oyvind
  • 568
  • 2
  • 6
  • 22
  • I think your way is ok. The XmlSerializer does not play very nicely for models like you're describing. there are some tricks to doing this more generically but they depend on your `BaseClass` being encapsulated in a root element. You could possibly add this root element around your xml and then apply this method, or use your XmlInclude. see http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx – wal Nov 21 '11 at 14:02

1 Answers1

1

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.

Amit Rai Sharma
  • 4,015
  • 1
  • 28
  • 35
  • 1
    Thats correct, i can excpect certain types back, its 3-4 differnet types. I have tried constructor with (Type, Type[]) without luck.. it is actually the same as using XmlIncludeAttribute. – Oyvind Nov 21 '11 at 11:46