我有一个名为 的主类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();
}
}
}