问题描述
我有一个名为theGarage
的主类,其中包含我们的客户,供应商和工作类的实例.
I have a main class called theGarage
, which contains instances of our customer, supplier, and jobs classes.
我想将程序数据保存到XML文件,我使用了下面的代码(只是一个片段,我有与其他类匹配的代码).我想知道是否有一种更简便的方法,例如将整个theGarage类写入XML文件并读取它,而不必像下面那样编写所有这些代码.
I want to save the program data to an XML file, I have used the code below (just a snippet, I have matching code for the other classes). I am wondering if there is an easier way for me to do this, like write the whole theGarage class to an XML file and read it in without having to write all this code like I have below.
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
.请参阅文档此处.
There is much simpler way of serializing objects, use XmlSerializer
instead. See documentation here.
将您的车库序列化为文件的代码段如下所示:
Code snippet to serialize your garage to file could look like:
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);
以及用于从文件加载车库的代码:
And code to load garage from file:
using(var sr = new StreamReader(@"c:\temp\garage.xml"))
{
garage = (theGarage)xs.Deserialize(sr);
}
这篇关于轻松地将整个类实例写入XML File并读回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!