3

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?

David Brabant
  • 41,623
  • 16
  • 83
  • 111
Chris Johnson
  • 1,230
  • 7
  • 15

2 Answers2

1

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);
L.B
  • 114,136
  • 19
  • 178
  • 224
0

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.

Michael Graczyk
  • 4,905
  • 2
  • 22
  • 34
  • In your example you modified the base type which i cant do. Even if i change the name of the derived type and add the XmlType("A") to ensure its deserialized correctly the serializer will see a clash between the two. – Chris Johnson Jun 20 '12 at 02:38
  • By the way, that confusion alone should be enough to convince you to change the name of your subclass. Why would you give them the same name? You're just asking for things to go wrong. – Michael Graczyk Jun 20 '12 at 04:25
  • Think about what you want the Xml to look like. It sounds like you want to serialize and derserialize your "A" instead of the base class "A". In that case you should be using composition instead of inheritance. – Michael Graczyk Jun 20 '12 at 04:27