views:

77

answers:

2

I've used XmlSerializer for a bunch of years without any problem. I started a new project and the class I made extended List. When I went to serialize the data, I lost the properties I added to my class. Obviously, I can fix this by changing around my class so it doesn't extent List anymore. I really was just wondering why XmlSerializer ignores the properties on the List.

var data = new Data { Number = 3 };
data.AddRange(Enumerable.Range(5, 5));
var serializer = new XmlSerializer(typeof(Data));
var memoryStream = new MemoryStream();
serializer.Serialize(memoryStream, data);
memoryStream.Position = 0;
var dataSerialized = new StreamReader(memoryStream).ReadToEnd();

public class Data : List<int>
{
 public int Number
 {
  get;
  set;
 }
}

After the code snippet above dataSerialized looks like this (its missing the 'Number' property):

<?xml version="1.0"?>
<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <int>5</int>
  <int>6</int>
  <int>7</int>
  <int>8</int>
  <int>9</int>
</ArrayOfInt>
+6  A: 

This is by design, basically the decision was made to handle collections as arrays not as classes with members, so collections would look like arrays on the wire, therefore they do not have any members other than collection items, and can be “flattened” by adding the [XmlElement] to the member of the ICollection type.

What you can do is implement IXmlSerializable and do custom serialization, however personally I prefer the DataContract way.

Yannick M.
Very clear answer
Rex M
+1  A: 

See the accepted answer to one of my own questions (Ignore the question itself as it misses the point completely). The XmlSerializer will only serialize the Items collection of a Collection, never its properties.

Dabblernl