XML Serialization Derived Types Problem Can be resolved!

I wanted to share with you a solution I found to a long annoying problem I had with C# Automatic XML Serialization.

Advertisements

Hi,

I wanted to share with you a solution I found to a long annoying problem I had with C# Automatic XML Serialization.

Some of you may know this solution, but it is important so everyone should know that.

The background is XML Serialization of objects. C# gives us an automatic method to serialize object by using XMLSerializer.

For example serialize object A like this:

Class Base{}

Class DerivedBase : Base{}

Class A

{

Base b;

DerivedBase db;

public virtual XmlSerializer ser { get { return new XmlSerializer(typeof (A)); } }

public override string ToString()

{

var sw = new StringWriter();

ser.Serialize(sw, this);

sw.Close();

return sw.ToString();

}

}

Now if we call A.ToString() we will get this Exception:

“The type namespace.DerivedBase was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically”

Usually the solution is to add XMLInclude to Class Base:

[System.Xml.Serialization.XmlInclude(typeof(DerivedBase))]

Class Base{}

But 2 problems can rise in this implementation:

  1. What if DerivedBase is not in the namespace of class Base, or even worse in a project that depends on Base namespace, so Base cannot XMLInclude DerivedBase
  2. What if we only have class Base as a dll ,so again  Base cannot XMLInclude DerivedBase

Till now I used only this method while trying to be truth to the class and namespace inheritance structure, but now I confronted with some class that I don’t wanted to move to the DerivedBase Project.

So the solution to the 2 problems is by using XmlSerializer Constructor (Type, array<Type>[]()[]) :

XmlSerializer ser = new XmlSerializer(typeof(A), new Type[]{ typeof(DerivedBase)});

And even if class B will inherit A, and have some DerivedDerivedBase property, it can override the XmlSerializer ser property with its own XmlSerializer.

Hope it could help you like it helped me…