0

I've looked here (and elsewhere) for any answers to this question, and I haven't found anything.

I have a class that derives from List, and contains another List. When I serialize to XML, the contents of the inner collection is not included.

Here's a very simple example:

[Serializable()]
public class MyList<T> : List<T>
{
    protected List<T> _nestedList= new List<T>();

    public List<T> NestedList
    {
        get { return _nestedList; }
        set { _nestedList = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyList<int> ints = new MyList<int>();
        ints.Add(1);
        ints.Add(2);
        ints.NestedList.Add(3);
        ints.NestedList.Add(4);

        string xml;
        var xmlSerializer = new XmlSerializer(ints.GetType());
        using (var memoryStream3 = new MemoryStream())
        {
            xmlSerializer.Serialize(memoryStream3, ints);
            xml = Encoding.UTF8.GetString(memoryStream3.ToArray());
        }
    }
}

Here's the xml string:

<?xml version="1.0"?>
<ArrayOfInt xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <int>1</int>
  <int>2</int>
</ArrayOfInt>

Notice the lack of NestedList.

I've tried various attributes on NestedList, such as XmlArray, or XmlArrayItem, but those didn't work.

I also know that this won't deserialize correctly. The real model is more complicated than this; this collection is inside of another object, which is also marked as Serializable.

The behavior is the same: the outer list serializes, but the inner does not. I'm trying to narrow down the problem, so I'm presenting this smaller example.

Thanks in advance!

EDIT: It looks like this is by design, and that the XmlSerializer doesn't include properties of a collection during serialization. So I'd have to do custom serialization.

Phil Mar
  • 91
  • 10
  • possible duplicate of [When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes](http://stackoverflow.com/questions/5069099/when-a-class-is-inherited-from-list-xmlserializer-doesnt-serialize-other-att) – BartoszKP Oct 28 '14 at 17:19

1 Answers1

0

Just to mark this as answered, it's by design in the XmlSerializer.

Phil Mar
  • 91
  • 10