I have several suggestions and a nice working example for you. First of all, I suggest a different class structure that takes advantage of class hierarchy.
Here is what you need:
- CarList - A wrapper class for managing your list of Cars
- Car - A class that provides all of the basic Car properties and methods
- BMW - A specific type of Car class. It inherits the parent Car class and provides additional properties and methods.
When you want to add more Car types, you would create another class and have it also inherit from the Car class.
On to the code...
Here is your CarList class. Notice that the List of Car objects has multiple XmlElement declarations on it. This is so that the serialization/de-serialization knows how to handle the different Car types. As you add more types, you will have to add a line here to describe the type.
Also, notice the static Save and Load methods that handle the serialization/de-serialization.
[XmlRoot("CarList")]
public class CarList
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlElement("Cars")]
[XmlElement("BWM", typeof(BMW))]
[XmlElement("Acura", typeof(Acura))]
//[XmlArrayItem("Honda", typeof(Honda))]
public List<Car> Cars { get; set; }
public static CarList Load(string xmlFile)
{
CarList carList = new CarList();
XmlSerializer s = new XmlSerializer(typeof(CarList));
TextReader r = new StreamReader(xmlFile);
carList = (CarList)s.Deserialize(r);
r.Close();
return carList;
}
public static void Save(CarList carList, string fullFilePath)
{
XmlSerializer s = new XmlSerializer(typeof(CarList));
TextWriter w = new StreamWriter(fullFilePath);
// use empty namespace to remove namespace declaration
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
s.Serialize(w, carList, ns);
w.Close();
}
}
Next, here is your Car class...
public class Car
{
// put properties and methods common to all car types here
[XmlAttribute("Id")]
public long Id { get; set; }
}
And finally, your specific Car types...
public class BMW : Car
{
// put properties and methods specific to this type here
[XmlAttribute("NavVendor")]
public string navigationSystemVendor { get; set; }
}
public class Acura : Car
{
// put properties and methods specific to this type here
[XmlAttribute("SunroofTint")]
public bool sunroofTint { get; set; }
}
Load your CarList like this:
CarList carList = CarList.Load(@"C:\cars.xml");
Make some changes, then Save your CarList like this:
CarList.Save(carList, @"C:\cars.xml");
And here is what the XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<CarList Name="My Car List">
<BWM Id="1234" NavVendor="Alpine" />
<Acura Id="2345" SunroofTint="true" />
</CarList>
Hope that helps get you started in the right direction!