15 January 2012

XmlSerializer inheritance woes

OK, this just drove me crazy for about an hour. I'm using the XmlSerializer, and my object graph has derived types.

I was using the XmlInclude attribute in the correct manner, but I still kept getting:

The type Child was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

It didn't work when I passed the extraTypes parameter to the XmlSerializer constructor either.

In the end it turns out that the 'Namespace' declaration was the problem. Adding an identical namepsace to the Child class fixed the problem. Strange because up until using inheritance things have worked fine only specifying it on the root class.

[XmlRoot(Namespace = "somenamespace")]
public class Root
{
public Parent Field { get; set; }
}

[XmlInclude(typeof(Child))]
public class Parent
{
public string Data { get; set; }
}

public class Child : Parent
{
}

...
Root r = new Root();
r.Field = new Child();

No comments: