Inherit XMLType from base class

I have the following base class decorated with XmlType attribute

[Serializable]
[XmlType("Base")]
public class Base
{
    [XmlElement(ElementName = "IdBase")]
    public int IdBase { get; set; }
    ...
}

      

And the following Inherited class, without , assigns the XMLType class to the decoration 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 expect because I wasn't explicitly styled with the XmlType)

<InheirtedClass1>
    <IdBase>1</IdBase>
    <InheritedProp>1</InheritedProp>
    ...
</InheirtedClass1>

      

This is the expected XML

<Base>
    <IdBase>1</IdBase>
    <InheritedProp>1</InheritedProp>
    ...
</Base>

      

If I try to decorate an inherited class with the [XmlType ("Base")] attribute but an exception is thrown when I instantiate the XmlSerializer (typeof (InheirtedClass1)) because it duplicates the XmlType, which makes sense ...

Can anyone explain why this is happening (replace the XmlType without explication to force it) and how can I achieve the desired behavior?

+3


source to share


1 answer


I achieved the desired behavior by simply decorating the base class with an XmlInclude attribute, ending with the following, and using an 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 Mark Gravell's answer on the following question (on my first search, I could not find this question, which is the main one for me)

fooobar.com/questions/533050 / ...

+4


source







All Articles