Chris Johnson
Chris Johnson

Reputation: 1350

How to force XML deserialization to derived types of the same name?

I have types provided in a library I cant modify, such as this:

namespace BaseNamespace
{
    public class A
    {
        public string Foo { get; set; }
    }
}

I also have a class named SomeOtherNamespace.A" that derives from BaseNamespace.A like this:

namespace SomeOtherNamespace
{
    public class A : BaseNamespace.A
    {
        public string DoSomething() {}
    }
}

From a web service I receive an XML payload with in it.

I want to deserialize the XML so that I end up with a SomeOtherNamespace.A object. However when I run the following code

string xml = "<A Foo=\"test\"></A>";

XmlSerializer serializer = new XmlSerializer(typeof(A));

StringReader reader = new StringReader(xml);

A obj = serializer.Deserialize(reader) as A;

I get an error:

Types 'BaseNamespace.A' and 'SomeOtherNamespace.A' both use the XML type name, 'A', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

Question: Without modification of the class BaseNamespace.A how can I force deserialization to my derived type SomeOtherNamespace.A?

Upvotes: 3

Views: 2173

Answers (2)

Michael Graczyk
Michael Graczyk

Reputation: 4965

If it is acceptable to use a different name in Xml for SomeOtherNamespace.A, you can just use XmlTypeAttribute to give A a different Xml type.

namespace SomeOtherNamespace {
    [XmlType("NotA")]
    public class A
    {
        public string Foo { get; set; }
    }
}

More importantly, you may want to consider a design in which your derived class does not have the same name as the base class.

Upvotes: 0

L.B
L.B

Reputation: 116178

Rename your SomeOtherNamespace.A as

namespace SomeOtherNamespace
{
    public class AAA : BaseNamespace.A
    {
        public string DoSomething() {}
    }

}

and create serializer as

XmlRootAttribute root = new XmlRootAttribute("A");
XmlSerializer serializer = new XmlSerializer(typeof(AAA),root);

Upvotes: 1

Related Questions