私はいくつかの提案とあなたのための素晴らしい実用的な例を持っています. まず、クラス階層を利用した別のクラス構造を提案します。
必要なものは次のとおりです。
- CarList - 車のリストを管理するためのラッパー クラス
- Car - すべての基本的な Car プロパティとメソッドを提供するクラス
- BMW - Car クラスの特定のタイプ。親の Car クラスを継承し、追加のプロパティとメソッドを提供します。
さらに Car タイプを追加する場合は、別のクラスを作成し、Car クラスから継承するようにします。
コードに...
これが CarList クラスです。Car オブジェクトの List には複数の XmlElement 宣言があることに注意してください。これは、シリアライゼーション/デシリアライゼーションがさまざまな種類の車を処理する方法を認識できるようにするためです。さらにタイプを追加すると、ここにタイプを説明する行を追加する必要があります。
また、シリアライゼーション/デシリアライゼーションを処理する静的な Save メソッドと Load メソッドにも注意してください。
[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();
}
}
次に、これが Car クラスです...
public class Car
{
// put properties and methods common to all car types here
[XmlAttribute("Id")]
public long Id { get; set; }
}
そして最後に、あなたの特定の車のタイプ...
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; }
}
次のように CarList をロードします。
CarList carList = CarList.Load(@"C:\cars.xml");
いくつかの変更を加えてから、次のように CarList を保存します。
CarList.Save(carList, @"C:\cars.xml");
XML は次のようになります。
<?xml version="1.0" encoding="utf-8"?>
<CarList Name="My Car List">
<BWM Id="1234" NavVendor="Alpine" />
<Acura Id="2345" SunroofTint="true" />
</CarList>
あなたが正しい方向に進むのに役立つことを願っています!