The XmlSerializer class provides a great way to convert (serialize) objects to XML and back (deserialize). However, it can be difficult to properly serialize collections such as Arrays and ArrayLists unless you know a few tricks. This sample application demonstrates how multiple car class instances can be added into an Array as well as an ArrayList and then be serialized into an XML structure. This serialization process is accomplished by using special XML serialization attributes such as XmlArray and XmlArrayItem found in the System.Xml.Serialization namespace. For example, the following code demonstrates how the type within an ArrayList can be identified using the XmlArrayItem attribute along with the typeof keyword:
[XmlArray("carsArrayList")]
[XmlArrayItem("car",typeof(Car))]
public ArrayList CarsCollection {
get {
return _CarsList;
}
set {
_CarsList = value;
}
}
To see the code in action, run the example below. Source code details are also available to view.
|