我有一个名为theGarage
的主类,其中包含我们的客户,供应商和工作类的实例。
我想将程序数据保存到XML文件,我已经使用了下面的代码(只是一个片段,我有其他类的匹配代码)。我想知道是否有一种更简便的方法,例如将整个theGarage类写入XML文件并读取它,而不必像下面那样编写所有这些代码。
public void saveToFile()
{
using (XmlWriter writer = XmlWriter.Create("theGarage.xml"))
{
writer.WriteStartDocument();
///
writer.WriteStartElement("theGarage");
writer.WriteStartElement("Customers");
foreach (Customer Customer in Program.theGarage.Customers)
{
writer.WriteStartElement("Customer");
writer.WriteElementString("FirstName", Customer.FirstName);
writer.WriteElementString("LastName", Customer.LastName);
writer.WriteElementString("Address1", Customer.Address1);
writer.WriteElementString("Address2", Customer.Address2);
writer.WriteElementString("Town", Customer.Town);
writer.WriteElementString("County", Customer.County);
writer.WriteElementString("PostCode", Customer.Postcode);
writer.WriteElementString("TelephoneHome", Customer.TelephoneHome);
writer.WriteElementString("TelephoneMob", Customer.TelephoneMob);
//begin vehicle list
writer.WriteStartElement("Vehicles");
foreach (Vehicle Vehicle in Customer.Cars)
{
writer.WriteStartElement("Vehicle");
writer.WriteElementString("Make", Vehicle.Make);
writer.WriteElementString("Model", Vehicle.Model);
writer.WriteElementString("Colour", Vehicle.Colour);
writer.WriteElementString("EngineSize", Vehicle.EngineSize);
writer.WriteElementString("Registration", Vehicle.Registration);
writer.WriteElementString("Year", Vehicle.YearOfFirstReg);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
最佳答案
序列化对象的方法要简单得多,请使用XmlSerializer
代替。请参阅文档here。
将车库序列化为文件的代码片段如下所示:
var garage = new theGarage();
// TODO init your garage..
XmlSerializer xs = new XmlSerializer(typeof(theGarage));
TextWriter tw = new StreamWriter(@"c:\temp\garage.xml");
xs.Serialize(tw, garage);
并从文件加载车库的代码:
using(var sr = new StreamReader(@"c:\temp\garage.xml"))
{
garage = (theGarage)xs.Deserialize(sr);
}