My scenario:
I have an object that I have defined with properties that are decorated with XmlElement tags and that have types that I have defined, some of which are typed as abstract that get set to respective derived types. I want to serialize this entire object into XML using XmlSerializer, and all properties that are abstract should get serialized as elements with TypeName set to the TypeName of the derived type.
This is an example of how the objects are structured:
[XmlType(TypeName = "MAINOBJECT")]
public class MainObject
{
[XmlElement(Type = typeof(DerivedClass))]
public BaseClass TheBase { get; set; }
}
[XmlInclude(typeof(DerivedClass))]
public abstract class BaseClass
{
[XmlAttribute("AnAttribute")]
public string AnAttribute { get; set; }
[XmlElement("ANELEMENT")]
public string AnElement { get; set; }
}
[XmlType(TypeName = "DERIVEDCLASS")]
public class DerivedClass : BaseClass
{
[XmlElement("ANOTHERELEMENT")]
public string AnotherElement { get; set; }
}
Note, however, that when I create a new instance of MainObject, populate it's properties and serialize it, this is what the generated XML looks like:
<MAINOBJECT>
<BaseClass AnAttribute="">
<ANELEMENT/>
<ANOTHERELEMENT/>
</BaseClass>
</MAINOBJECT>
What I want is this:
<MAINOBJECT>
<DERIVEDCLASS AnAttribute="">
<ANELEMENT/>
<ANOTHERELEMENT/>
</DERIVEDCLASS>
</MAINOBJECT>
Any clue what I'm doing wrong here?
Add the XmlElement name to TheBase
in MainObject
as follows:
[XmlType(TypeName = "MAINOBJECT")]
public class MainObject
{
[XmlElement("DERIVEDCLASS", Type = typeof(DerivedClass))]
public BaseClass TheBase { get; set; }
}