如何从Windows窗体数据保存到一个XML文件?窗体、文件、数据、Windows

2023-09-07 03:56:20 作者:别留我独自一人

我pretty的肯定,我要创造某种东西的XML文件中有看起来像第一模具的,对吧?

I pretty sure I have to create some sort of mold of what the XML file has to look like first, right?

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

一个简单的方法来做到这一点是创建你把数据.NET类,然后使用XmlSerializer将数据序列化到一个文件,然后再反序列化回类的实例,并重新填充表单。

One simple way to do this would be to create .NET classes that you put the data in and then use XmlSerializer to serialize the data to a file and then later deserialize back into an instance of the class and re-populate the form.

作为一个例子,如果有与客户数据的形式。为了简化,我们就只能姓和名。您可以创建一个类来保存数据。请记住,这只是一个简单的例子,你可以存储阵列和各种复杂/嵌套的数据是这样的。

AS an example, if you have a form with customer data. To keep it short we will just have first name and last name. You can create a class to hold the data. Keep in mind this is just a simple example, you can store arrays and all kinds of complex/nested data like this.

public class CustomerData
{
  public string FirstName;
  public string LastName;
}

所以保存为XML的code会是这个样子的数据。

So save the data as XML your code will look something like this.

// 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);
}

和装载数据后面会像下面这样

And loading the data back would be something like the following

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;
}
 
精彩推荐