我相信我需要首先创建一个XML文件的模板,对吗?
任何帮助将不胜感激。
一个简单的方法是创建.NET类,在其中放置数据,然后使用XmlSerializer将数据序列化到文件中,稍后反序列化回类实例并重新填充表单。
以客户数据的表单为例,为了简洁起见,我们只包含名字和姓氏。您可以创建一个类来保存这些数据。请记住,这只是一个简单的示例,您可以像这样存储数组和各种复杂/嵌套的数据。
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;
}
XmlSerializer
重新保存它。 - Arenclass
而不是 struct
? - dlras2看看使用Linq to xml - http://msdn.microsoft.com/en-us/library/bb387098.aspx 这里有一些教程,将指导您创建和查询XML文档。
所以,您想从Windows表单应用程序中收集用户数据,然后在他们点击“确定”时将其写入XML文件吗?如果是这样,我建议您查看XmlTextWriter类(http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx)。