<p>Following on from my <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods">previous question</a> I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).</p>

<p>The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types.</p>

<p>I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case!</p>

<p>So I have done some digging on Google and I now understand <em>why</em> it's not working. In that <strong>the <code>XmlSerializer</code> is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to</strong>. Fine.</p>

<p>I did come across <a href="http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx" rel="noreferrer">this page</a> on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible.</p>

<p>One thing I should also add is that I <strong>DO NOT</strong> want to go down the <code>XmlInclude</code> route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!</p>

[{'answer_id': 20097, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 1, 'selected': False, 'text': "<p>I've done things similar to this. What I normally do is make sure all the XML serialization attributes are on the concrete class, and just have the properties on that class call through to the base classes (where required) to retrieve information that will be de/serialized when the serializer calls on those properties. It's a bit more coding work, but it does work much better than attempting to force the serializer to just do the right thing.</p>\n"}, {'answer_id': 20098, 'author': 'Shaun Austin', 'author_id': 1120, 'author_profile': 'https://Stackoverflow.com/users/1120', 'pm_score': 3, 'selected': False, 'text': '<p>One thing to look at is the fact that in the XmlSerialiser constructor you can pass an array of types that the serialiser might be having difficulty resolving. I\'ve had to use that quite a few times where a collection or complex set of datastructures needed to be serialised and those types lived in different assemblies etc.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/e5aakyae.aspx" rel="nofollow noreferrer">XmlSerialiser Constructor with extraTypes param</a></p>\n\n<p>EDIT: I would add that this approach has the benefit over XmlInclude attributes etc that you can work out a way of discovering and compiling a list of your possible concrete types at runtime and stuff them in.</p>\n'}, {'answer_id': 20126, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Seriously, an extensible framework of POCOs will never serialize to XML reliably.  I say this because I can guarantee someone will come along, extend your class, and botch it up.</p>\n\n<p>You should look into using XAML for serializing your object graphs.  It is designed to do this, whereas XML serialization isn't.  </p>\n\n<p>The Xaml serializer and deserializer handles generics without a problem, collections of base classes and interfaces as well (as long as the collections themselves implement <code>IList</code> or <code>IDictionary</code>).  There are some caveats, such as marking your read only collection properties with the <code>DesignerSerializationAttribute</code>, but reworking your code to handle these corner cases isn't that hard.</p>\n"}, {'answer_id': 21958, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 2, 'selected': False, 'text': "<p>Just a quick update on this, I have not forgotten!</p>\n\n<p>Just doing some more research, looks like I am on to a winner, just need to get the code sorted.</p>\n\n<p>So far, I have the following:</p>\n\n<ul>\n<li>The <em>XmlSeralizer</em> is basically a class that does some nifty reflection on the classes it is serializing. It determines the properties that are serialized based on the <strong>Type</strong>.</li>\n<li>The reason the problem occurs is because a type mismatch is occurring, it is expecting the <em>BaseType</em> but in fact receives the <em>DerivedType</em> .. While you may think that it would treat it polymorphically, it doesn't since it would involve a whole extra load of reflection and type-checking, which it is not designed to do.</li>\n</ul>\n\n<p>This behaviour appears to be able to be overridden (code pending) by creating a proxy class to act as the go-between for the serializer. This will basically determine the type of the derived class and then serialize that as normal. This proxy class then will feed that XML back up the line to the main serializer..</p>\n\n<p>Watch this space! ^_^</p>\n"}, {'answer_id': 392690, 'author': 'Max Galkin', 'author_id': 2351099, 'author_profile': 'https://Stackoverflow.com/users/2351099', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s certainly a solution to your problem, but there is another problem, which somewhat undermines your intention to use "portable" XML format. Bad thing happens when you decide to change classes in the next version of your program and you need to support both formats of serialization -- the new one and the old one (because your clients still use thier old files/databases, or they connect to your server using old version of your product). But you can\'t use this serializator anymore, because you used </p>\n\n<pre><code>type.AssemblyQualifiedName\n</code></pre>\n\n<p>which looks like</p>\n\n<pre><code>TopNamespace.SubNameSpace.ContainingClass+NestedClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089\n</code></pre>\n\n<p>that is contains your assembly attributes and version...</p>\n\n<p>Now if you try to change your assembly version, or you decide to sign it, this deserialization is not going to work...</p>\n'}, {'answer_id': 985495, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 7, 'selected': True, 'text': '<h2>Problem Solved!</h2>\n<p>OK, so I finally got there (admittedly with a <strong>lot</strong> of help from <a href="http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx" rel="noreferrer">here</a>!).</p>\n<p>So summarise:</p>\n<h3>Goals:</h3>\n<ul>\n<li>I didn\'t want to go down the <em>XmlInclude</em> route due to the maintenence headache.</li>\n<li>Once a solution was found, I wanted it to be quick to implement in other applications.</li>\n<li>Collections of Abstract types may be used, as well as individual abstract properties.</li>\n<li>I didn\'t really want to bother with having to do &quot;special&quot; things in the concrete classes.</li>\n</ul>\n<h3>Identified Issues/Points to Note:</h3>\n<ul>\n<li><em>XmlSerializer</em> does some pretty cool reflection, but it is <em>very</em> limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses).</li>\n<li>The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a <strong>tight coupling</strong> between the class and the serializer (not good).</li>\n<li>We can implement our own XmlSerializer by creating a class that implements <em>IXmlSerializable</em> .</li>\n</ul>\n<h2>The Solution</h2>\n<p>I created a generic class, in which you specify the generic type as the abstract type you will be working with. This gives the class the ability to &quot;translate&quot; between the abstract type and the concrete type since we can hard-code the casting (i.e. we can get more info than the XmlSerializer can).</p>\n<p>I then implemented the <em>IXmlSerializable</em> interface, this is pretty straight forward, but when serializing we need to ensure we write the type of the concrete class to the XML, so we can cast it back when de-serializing. It is also important to note it must be <strong>fully qualified</strong> as the assemblies that the two classes are in are likely to differ. There is of course a little type checking and stuff that needs to happen here.</p>\n<p>Since the XmlSerializer cannot cast, we need to provide the code to do that, so the implicit operator is then overloaded (I never even knew you could do this!).</p>\n<p>The code for the AbstractXmlSerializer is this:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml.Serialization;\n\nnamespace Utility.Xml\n{\n    public class AbstractXmlSerializer&lt;AbstractType&gt; : IXmlSerializable\n    {\n        // Override the Implicit Conversions Since the XmlSerializer\n        // Casts to/from the required types implicitly.\n        public static implicit operator AbstractType(AbstractXmlSerializer&lt;AbstractType&gt; o)\n        {\n            return o.Data;\n        }\n\n        public static implicit operator AbstractXmlSerializer&lt;AbstractType&gt;(AbstractType o)\n        {\n            return o == null ? null : new AbstractXmlSerializer&lt;AbstractType&gt;(o);\n        }\n\n        private AbstractType _data;\n        /// &lt;summary&gt;\n        /// [Concrete] Data to be stored/is stored as XML.\n        /// &lt;/summary&gt;\n        public AbstractType Data\n        {\n            get { return _data; }\n            set { _data = value; }\n        }\n\n        /// &lt;summary&gt;\n        /// **DO NOT USE** This is only added to enable XML Serialization.\n        /// &lt;/summary&gt;\n        /// &lt;remarks&gt;DO NOT USE THIS CONSTRUCTOR&lt;/remarks&gt;\n        public AbstractXmlSerializer()\n        {\n            // Default Ctor (Required for Xml Serialization - DO NOT USE)\n        }\n\n        /// &lt;summary&gt;\n        /// Initialises the Serializer to work with the given data.\n        /// &lt;/summary&gt;\n        /// &lt;param name=&quot;data&quot;&gt;Concrete Object of the AbstractType Specified.&lt;/param&gt;\n        public AbstractXmlSerializer(AbstractType data)\n        {\n            _data = data;\n        }\n\n        #region IXmlSerializable Members\n\n        public System.Xml.Schema.XmlSchema GetSchema()\n        {\n            return null; // this is fine as schema is unknown.\n        }\n\n        public void ReadXml(System.Xml.XmlReader reader)\n        {\n            // Cast the Data back from the Abstract Type.\n            string typeAttrib = reader.GetAttribute(&quot;type&quot;);\n\n            // Ensure the Type was Specified\n            if (typeAttrib == null)\n                throw new ArgumentNullException(&quot;Unable to Read Xml Data for Abstract Type \'&quot; + typeof(AbstractType).Name +\n                    &quot;\' because no \'type\' attribute was specified in the XML.&quot;);\n\n            Type type = Type.GetType(typeAttrib);\n\n            // Check the Type is Found.\n            if (type == null)\n                throw new InvalidCastException(&quot;Unable to Read Xml Data for Abstract Type \'&quot; + typeof(AbstractType).Name +\n                    &quot;\' because the type specified in the XML was not found.&quot;);\n\n            // Check the Type is a Subclass of the AbstractType.\n            if (!type.IsSubclassOf(typeof(AbstractType)))\n                throw new InvalidCastException(&quot;Unable to Read Xml Data for Abstract Type \'&quot; + typeof(AbstractType).Name +\n                    &quot;\' because the Type specified in the XML differs (\'&quot; + type.Name + &quot;\').&quot;);\n\n            // Read the Data, Deserializing based on the (now known) concrete type.\n            reader.ReadStartElement();\n            this.Data = (AbstractType)new\n                XmlSerializer(type).Deserialize(reader);\n            reader.ReadEndElement();\n        }\n\n        public void WriteXml(System.Xml.XmlWriter writer)\n        {\n            // Write the Type Name to the XML Element as an Attrib and Serialize\n            Type type = _data.GetType();\n\n            // BugFix: Assembly must be FQN since Types can/are external to current.\n            writer.WriteAttributeString(&quot;type&quot;, type.AssemblyQualifiedName);\n            new XmlSerializer(type).Serialize(writer, _data);\n        }\n\n        #endregion\n    }\n}\n</code></pre>\n<p>So, from there, how do we tell the XmlSerializer to work with our serializer rather than the default? We must pass our type within the Xml attributes type property, for example:</p>\n<pre><code>[XmlRoot(&quot;ClassWithAbstractCollection&quot;)]\npublic class ClassWithAbstractCollection\n{\n    private List&lt;AbstractType&gt; _list;\n    [XmlArray(&quot;ListItems&quot;)]\n    [XmlArrayItem(&quot;ListItem&quot;, Type = typeof(AbstractXmlSerializer&lt;AbstractType&gt;))]\n    public List&lt;AbstractType&gt; List\n    {\n        get { return _list; }\n        set { _list = value; }\n    }\n\n    private AbstractType _prop;\n    [XmlElement(&quot;MyProperty&quot;, Type=typeof(AbstractXmlSerializer&lt;AbstractType&gt;))]\n    public AbstractType MyProperty\n    {\n        get { return _prop; }\n        set { _prop = value; }\n    }\n\n    public ClassWithAbstractCollection()\n    {\n        _list = new List&lt;AbstractType&gt;();\n    }\n}\n</code></pre>\n<p>Here you can see, we have a collection and a single property being exposed, and all we need to do is add the <em>type</em> named parameter to the Xml declaration, easy! :D</p>\n<p><strong>NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community :)</strong></p>\n<p>Now, but unsure as to what to do with answers here since they all had their pro\'s and con\'s. I\'ll upmod those that I feel were useful (no offence to those that weren\'t) and close this off once I have the rep :)</p>\n<p>Interesting problem and good fun to solve! :)</p>\n'}, {'answer_id': 26373293, 'author': 'user2009677', 'author_id': 2009677, 'author_profile': 'https://Stackoverflow.com/users/2009677', 'pm_score': 1, 'selected': False, 'text': '<p>Even better, using notation:</p>\n\n<pre><code>[XmlRoot]\npublic class MyClass {\n    public abstract class MyAbstract {} \n    public class MyInherited : MyAbstract {} \n    [XmlArray(), XmlArrayItem(typeof(MyInherited))] \n    public MyAbstract[] Items {get; set; } \n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/20084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832/']