Search code examples
c#listxml-serializationienumerablexmlserializer

XmlSerializer doesn't serialize everything in my class


I have a very basic class that is a list of sub-classes, plus some summary data.

[Serializable]
public class ProductCollection : List<Product>
{
    public bool flag { get; set; }
    public double A { get; set; }
    public double B { get; set; }
    public double C { get; set; }
}


// method to save this class
private void SaveProductCollection()
{
    // Export case as XML...
    XmlSerializer xml = new XmlSerializer(typeof(ProductCollection));
    StreamWriter sw = new StreamWriter("output.xml");
    xml.Serialize(sw, theCollection);
    sw.Close();
}

When I call SaveProductCollection() I get the following:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Product>
    <InputType>1</InputType>
  </Product>
  <Product>
    <InputType>1</InputType>
  </Product>
</ArrayOfProduct>

Note that I have the base type : List<Product>. But I don't have any of the class properties: flag, A, B, C.

Did I do something wrong? What's up??

UPDATE Thanks for the replies. I wasn't aware that it was by-design. I've converted to BinaryFormatter (for binary serialization instead) and it works wonderfully.


Solution

  • Following msdn:

    Q: Why aren't all properties of collection classes serialized?

    A: The XmlSerializer only serializes the elements in the collection when it detects either the IEnumerable or the ICollection interface. This behavior is by design. The only work around is to re-factor the custom collection into two classes, one of which exposes the properties including one of the pure collection types.