【问题标题】:How can I save data from a Windows Form to an XML file?如何将数据从 Windows 窗体保存到 XML 文件?
【发布时间】:2010-05-20 19:53:29
【问题描述】:

我很确定我必须先创建某种 XML 文件的模型,对吧?

任何帮助将不胜感激。

【问题讨论】:

  • 不一定。您可以开始直接写入 XDocument 对象,然后使用 XDocument.Save(filename) 方法保存到文件。

标签: c# xml .net-3.5


【解决方案1】:

执行此操作的一种简单方法是创建将数据放入其中的 .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 这是我建议的方法。您可能遇到的唯一问题是,如果您的数据发生更改,旧版本将不会始终正确反序列化为 DataObject。您必须编写一个转换器来将 XML 更新为新模式,或者为 xml 编写一个备用加载器(基于旧模式),然后使用 XmlSerializer 重新保存它
  • 您有什么理由决定使用class 而不是struct
  • @cyclotis04,结构体适用于较小的不可变数据。您最终会将数据类的实例传递到应用程序的其他部分,因此传递引用对于大型数据结构来说既好又高效。这可能是典型的 struct 与 class 的讨论,对我来说,除非我真的了解需求并看到使用 struct 的价值,否则我通常会使用类,但这只是我的经验法则。
  • 我还想补充一下这个问题,并询问您如何使用数组或数据列表来处理此解决方案。
  • @RobertFleck - 创建一个包含数组或列表的类,然后序列化该类。这使您可以在需要时添加数组/列表以外的其他数据。
【解决方案2】:

看看使用 Linq to xml - http://msdn.microsoft.com/en-us/library/bb387098.aspx 这里有教程将指导您创建和查询 xml 文档。

【讨论】:

    【解决方案3】:

    那么,您是否希望在 Windows 表单应用程序中从用户那里收集数据,然后将其写入 XML 文件(当他们单击“确定”时)?如果是这样,我会查看 XmlTextWriter 类(http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      相关资源
      最近更新 更多