0

I have a scenario close to the one in this thread . I wanted to provide a more specific example but wasn't sure how to ask it on that thread and make it look pretty. So I started this one. I have a collection of BaseObjects within a class. I would like to Deserialize this class with the Xml output of the mixed collection of derived classes.

public class RootElementClass
{

    public BaseTypeCollection Collection{ get; set; }
}

public class BaseType { public int Id{get;set;} }
public class BaseTypeCollection : System.ComponentModel.BindingList<BaseType>{}
public class Derived1BaseType : BaseType { public string Derived1Name{get;set;} }
public class Derived2BaseType : BaseType { public string Derived2Name{get;set;} 
                                           public string DerivedOtherProperty{get;set;} }

How do I get an output of something like this:

<RootElementClass>
    <Collection>
        <BaseObject>
            <Id>...</Id>
            <Derived1Name>...</Derived1Name>
        </BaseObject>
        <BaseObject>
            <Id>...</Id>
            <Derived2Name>...</Derived2Name>
            <DerivedOtherProperty>...</DerivedOtherProperty>
        </BaseObject>
    </Collection>
</RootElementClass>
Community
  • 1
  • 1
mac
  • 485
  • 1
  • 6
  • 29
  • `XmlSerializer` doesn't support polymorphism in that format. It supports polymorphism by letting you change the element name, or letting you add an `xsi:type` attribute. See [XML Serialization of an object initialized as array](https://stackoverflow.com/questions/38212559/xml-serialization-of-an-object-initialized-as-array/38217120#38217120). – dbc Nov 14 '16 at 19:13
  • I do not know how to do it 100% by compile time code (or if that is possible), but you could always create a function that supplies your Project's known types and version (version, in case you add something to your class at a later time): **Deserialize(String className, String classVersion)**. –  Nov 14 '16 at 19:40
  • What about using a single class and hidding null values as described in this post http://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values – fvasquezc23 Nov 14 '16 at 20:32
  • I think I did something like this by implementing the IXmlSerializable interface but it was a lot of work. – Pawel Nov 14 '16 at 21:32

0 Answers0