Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 234547
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T20:11:36+00:00 2026-05-11T20:11:36+00:00

Following on from my previous question I have been working on getting my object

  • 0

Following on from my previous question I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).

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.

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!

So I have done some digging on Google and I now understand why it’s not working. In that the XmlSerializer 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. Fine.

I did come across this page 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.

One thing I should also add is that I DO NOT want to go down the XmlInclude 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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T20:11:37+00:00Added an answer on May 11, 2026 at 8:11 pm

    Problem Solved!

    OK, so I finally got there (admittedly with a lot of help from here!).

    So summarise:

    Goals:

    • I didn’t want to go down the XmlInclude route due to the maintenence headache.
    • Once a solution was found, I wanted it to be quick to implement in other applications.
    • Collections of Abstract types may be used, as well as individual abstract properties.
    • I didn’t really want to bother with having to do "special" things in the concrete classes.

    Identified Issues/Points to Note:

    • XmlSerializer does some pretty cool reflection, but it is very limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses).
    • The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a tight coupling between the class and the serializer (not good).
    • We can implement our own XmlSerializer by creating a class that implements IXmlSerializable .

    The Solution

    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 "translate" 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).

    I then implemented the IXmlSerializable 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 fully qualified 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.

    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!).

    The code for the AbstractXmlSerializer is this:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml.Serialization;
    
    namespace Utility.Xml
    {
        public class AbstractXmlSerializer<AbstractType> : IXmlSerializable
        {
            // Override the Implicit Conversions Since the XmlSerializer
            // Casts to/from the required types implicitly.
            public static implicit operator AbstractType(AbstractXmlSerializer<AbstractType> o)
            {
                return o.Data;
            }
    
            public static implicit operator AbstractXmlSerializer<AbstractType>(AbstractType o)
            {
                return o == null ? null : new AbstractXmlSerializer<AbstractType>(o);
            }
    
            private AbstractType _data;
            /// <summary>
            /// [Concrete] Data to be stored/is stored as XML.
            /// </summary>
            public AbstractType Data
            {
                get { return _data; }
                set { _data = value; }
            }
    
            /// <summary>
            /// **DO NOT USE** This is only added to enable XML Serialization.
            /// </summary>
            /// <remarks>DO NOT USE THIS CONSTRUCTOR</remarks>
            public AbstractXmlSerializer()
            {
                // Default Ctor (Required for Xml Serialization - DO NOT USE)
            }
    
            /// <summary>
            /// Initialises the Serializer to work with the given data.
            /// </summary>
            /// <param name="data">Concrete Object of the AbstractType Specified.</param>
            public AbstractXmlSerializer(AbstractType data)
            {
                _data = data;
            }
    
            #region IXmlSerializable Members
    
            public System.Xml.Schema.XmlSchema GetSchema()
            {
                return null; // this is fine as schema is unknown.
            }
    
            public void ReadXml(System.Xml.XmlReader reader)
            {
                // Cast the Data back from the Abstract Type.
                string typeAttrib = reader.GetAttribute("type");
    
                // Ensure the Type was Specified
                if (typeAttrib == null)
                    throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +
                        "' because no 'type' attribute was specified in the XML.");
    
                Type type = Type.GetType(typeAttrib);
    
                // Check the Type is Found.
                if (type == null)
                    throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +
                        "' because the type specified in the XML was not found.");
    
                // Check the Type is a Subclass of the AbstractType.
                if (!type.IsSubclassOf(typeof(AbstractType)))
                    throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +
                        "' because the Type specified in the XML differs ('" + type.Name + "').");
    
                // Read the Data, Deserializing based on the (now known) concrete type.
                reader.ReadStartElement();
                this.Data = (AbstractType)new
                    XmlSerializer(type).Deserialize(reader);
                reader.ReadEndElement();
            }
    
            public void WriteXml(System.Xml.XmlWriter writer)
            {
                // Write the Type Name to the XML Element as an Attrib and Serialize
                Type type = _data.GetType();
    
                // BugFix: Assembly must be FQN since Types can/are external to current.
                writer.WriteAttributeString("type", type.AssemblyQualifiedName);
                new XmlSerializer(type).Serialize(writer, _data);
            }
    
            #endregion
        }
    }
    

    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:

    [XmlRoot("ClassWithAbstractCollection")]
    public class ClassWithAbstractCollection
    {
        private List<AbstractType> _list;
        [XmlArray("ListItems")]
        [XmlArrayItem("ListItem", Type = typeof(AbstractXmlSerializer<AbstractType>))]
        public List<AbstractType> List
        {
            get { return _list; }
            set { _list = value; }
        }
    
        private AbstractType _prop;
        [XmlElement("MyProperty", Type=typeof(AbstractXmlSerializer<AbstractType>))]
        public AbstractType MyProperty
        {
            get { return _prop; }
            set { _prop = value; }
        }
    
        public ClassWithAbstractCollection()
        {
            _list = new List<AbstractType>();
        }
    }
    

    Here you can see, we have a collection and a single property being exposed, and all we need to do is add the type named parameter to the Xml declaration, easy! 😀

    NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community 🙂

    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 🙂

    Interesting problem and good fun to solve! 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 231k
  • Answers 231k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Use the following function like this: Image('/path/to/original.image', '1/1', '150*', './thumb.jpg');… May 13, 2026 at 2:13 am
  • Editorial Team
    Editorial Team added an answer Check you database schema to see if the field (referenced… May 13, 2026 at 2:13 am
  • Editorial Team
    Editorial Team added an answer I figured out the problem - there was a session… May 13, 2026 at 2:13 am

Related Questions

So I've been working on this all day and I can't figure out how
Following on from my previous question [link text][1] , I have a new problem.
This is a followup to my own previous question and I'm kind of embarassed
I have been trying to track down weird problems with my mod_wsgi/Python web application.

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.