Reputation: 400
I have the following base class decorated with the XmlType attribute
[Serializable]
[XmlType("Base")]
public class Base
{
[XmlElement(ElementName = "IdBase")]
public int IdBase { get; set; }
...
}
And the following Inherited class, without the XMLType attibute decorating class
[Serializable]
public class InheritedClass1 : Base
{
[XmlElement(ElementName = "InheritedProp")]
public int InheritedProp{ get; set; }
...
}
When I serialize, the inherited class seems to override the XmlType generating the following XML (which I didn´t expected because I didn´t decorated explicitly with the XmlType)
<InheirtedClass1>
<IdBase>1</IdBase>
<InheritedProp>1</InheritedProp>
...
</InheirtedClass1>
That´s the XML I expected
<Base>
<IdBase>1</IdBase>
<InheritedProp>1</InheritedProp>
...
</Base>
If I trying decorate the inherited class with the [XmlType("Base")] attribute, but an exception is thrown when I create an instance of the XmlSerializer(typeof(InheirtedClass1)) because it duplicates the XmlType, which makes sense...
Can someone explain why that happens (the XmlType be replaced without explict forcing it to) and how can I achieve the desired behavior?
Upvotes: 3
Views: 2264
Reputation: 400
I achieved the desired behavior, simply decorating the base class with the XmlInclude attribute ending up on the following and using the XmlSerializer of the base class type
[Serializable]
[XmlType("Base")]
[XmlInclude(typeof(InheritedClass1))] //Missing This line!
public class Base
{
[XmlElement(ElementName = "IdBase")]
public int IdBase { get; set; }
...
}
This answer is based on the Marc Gravell´s answer on the following question (On my first search, I was unable to find this question which is basiclly the same of mine)
https://stackoverflow.com/a/12237360/2237027
Upvotes: 4