如何将数据从XML恢复到Windows窗体中

本文关键字:Windows 窗体 恢复 XML 数据 | 更新日期: 2023-09-27 17:59:45

我保存了如下所示的数据,现在我想将XML数据恢复到相应的文本框中。

CustomerData customer = new CustomerData();    
customer.FirstName = first_name.Text;    
customer.RegNo = reg_no.Text;    
customer.Department = dept.Text;    
XmlSerializer xs = new XmlSerializer(typeof(CustomerData));    
using(FileStream fs = new FileStream(@"D:'Data.xml", FileMode.Create)) {
    xs.Serialize(fs, customer);
}
MessageBox.Show("Inserted");

如何将数据从XML恢复到Windows窗体中

XmlSerializer xs = new XmlSerializer(typeof(CustomerData));
using(FileStream fs = new FileStream(@"D:'Data.xml", FileMode.Open))
{
    CustomerData customer = (CustomerData)xs.Deserialize(fs);  
    first_name.Text = customer.FirstName;    
    reg_no.Text = customer.RegNo;    
    dept.Text = customer.Department; 
} 

更新如果要保存客户数据更改的历史记录并加载最后一次,请保存并加载CustomerData对象列表:

private List<CustomerData> GetCustomers(string filename)
{
    if (!File.Exists(filename))
        return new List<CustomerData>();
    XmlSerializer xs = new XmlSerializer(typeof(List<CustomerData>));
    using (FileStream fs = new FileStream(filename, FileMode.Open))
        return (List<CustomerData>)xs.Deserialize(fs);
}
public void SaveCustomers(string filename, List<CustomerData> customers)
{
    XmlSerializer xs = new XmlSerializer(typeof(List<CustomerData>));
    using (FileStream fs = new FileStream(filename, FileMode.Create))
        xs.Serialize(fs, customers);
}

并使用它来保存:

List<CustomerData> customers = GetCustomers(@"D:'Data.xml");
CustomerData customer = new CustomerData();
customer.FirstName = first_name.Text;
customer.RegNo = reg_no.Text;
customer.Department = dept.Text;
customers.Add(customer);
SaveCustomers(@"D:'Data.xml", customers);

和负载:

var customer = GetCustomers(@"D:'Data.xml").LastOrDefault();
if (customer != null)
{
    first_name.Text = customer.FirstName;
    reg_no.Text = customer.RegNo;
    dept.Text = customer.Department;
}