如何将Windows表单中的数据保存到XML文件?

3

我相信我需要首先创建一个XML文件的模板,对吗?

任何帮助将不胜感激。


不一定。您可以直接开始向XDocument对象编写,然后使用XDocument.Save(filename)方法保存到文件。 - Pretzel
3个回答

12

一个简单的方法是创建.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;
}

1
+1 这是我建议的方法。唯一可能遇到的问题是,如果您的数据发生更改,则旧版本不会始终正确反序列化为 DataObject。您需要编写转换器来将 XML 更新为新模式,或者编写基于旧模式的替代加载程序,然后使用 XmlSerializer 重新保存它。 - Aren
你为什么决定使用 class 而不是 struct - dlras2
1
@cyclotis04,对于较小的不可变数据,结构体是一个不错的选择。你最终会将数据类的实例传递给应用程序的其他部分,因此对于大型数据结构来说,传递引用是很好的选择。这可能是关于结构体与类的典型讨论,对我而言,除非我真正理解需要并看到使用结构体的价值,否则我通常会选择类,但这只是我的经验之谈。 - Chris Taylor
我也想借用这个问题,问一下如何使用数据的数组或列表来实现这个解决方案。 - Robert Fleck
@RobertFleck - 创建一个包含数组或列表的类,然后对该类进行序列化。这样可以在需要时添加除数组/列表之外的其他数据。 - Chris Taylor

1

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接