我非常确定我必须首先创建 XML 文件的某种模型,对吧?
任何帮助将不胜感激。
一种简单的方法是创建 .NET 类,将数据放入其中然后使用Xml序列化器 http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx将数据序列化到文件,然后反序列化回类的实例并重新填充表单。
举个例子,如果您有一个包含客户数据的表单。为了简短起见,我们只有名字和姓氏。您可以创建一个类来保存数据。请记住,这只是一个简单的示例,您可以像这样存储数组和各种复杂/嵌套数据。
public class CustomerData
{
public string FirstName;
public string LastName;
}
因此,将数据保存为 XML,您的代码将如下所示。
// Create an instance of the CustomerData class and populate
// it with the data from the form.
CustomerData customer = new CustomerData();
customer.FirstName = txtFirstName.Text;
customer.LastName = txtLastName.Text;
// Create and XmlSerializer to serialize the data to a file
XmlSerializer xs = new XmlSerializer(typeof(CustomerData));
using (FileStream fs = new FileStream("Data.xml", FileMode.Create))
{
xs.Serialize(fs, customer);
}
加载数据将类似于以下内容
CustomerData customer;
XmlSerializer xs = new XmlSerializer(typeof(CustomerData));
using (FileStream fs = new FileStream("Data.xml", FileMode.Open))
{
// This will read the XML from the file and create the new instance
// of CustomerData
customer = xs.Deserialize(fs) as CustomerData;
}
// If the customer data was successfully deserialized we can transfer
// the data from the instance to the form.
if (customer != null)
{
txtFirstName.Text = customer.FirstName;
txtLastName.Text = customer.LastName;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)