加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将数据从Windows窗体保存到XML文件?

发布时间:2020-12-16 00:13:43 所属栏目:百科 来源:网络整理
导读:我非常肯定我必须首先创建一些 XML文件的模型,对吧? 任何帮助将不胜感激. 解决方法 一种简单的方法是创建将数据放入的.NET类,然后使用 XmlSerializer将数据序列化为文件,然后反序列化为类的实例并重新填充表单. 例如,如果您有一个包含客户数据的表单.为了简
我非常肯定我必须首先创建一些 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读