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.