To be serializable via XmlSerializer
, your types must
- be public
- have a public parameterless constructor
- it serializes the public read/write fields and properties (properties being preferred)
In terms of which constructs;
- individual concrete entities are fine
- concrete lists/arrays (
List<T>
, T[]
, etc) are handled fine
- but it will struggle with interfaces, dictionaries, and various generics scenarios (other than lists)
You are right that List<T>
is fine for serializing a set of like objects. If you are dealing with subclasses, then [XmlInclude]
can be used to distinguish types; i.e. if you have:
var list = new List<ParentType>();
list.Add(new ParentType());
list.Add(new ChildType()); // Child : Parent
then this may still be serializable as long as you have:
[XmlInclude(typeof(Child))]
public class Parent {}
public class Child : Parent {}
(you can also specify this relationship in the ctor to XmlSerializer
, but it is extra work)
I don't recommend using IXmlSerializable
unless you have to; it is complex and hard to get right. More importantly; it doesn't work *at all if you are using wsdl-generated proxy objects over a SOAP service; the other end won't have your IXmlSerializable
implementation.
I also don't recommend serializing lists of arbitrary object types; if you have a finite set of known types there are tricks to do this utilising [XmlInclude]
etc.