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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With