如何从Windows窗体数据保存到一个XML文件? [英] How can I save data from a Windows Form to an XML file?

查看:472
本文介绍了如何从Windows窗体数据保存到一个XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我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类,然后使用<一个href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx">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;
}

这篇关于如何从Windows窗体数据保存到一个XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆