如何将数据从XML还原到Windows窗体?

时间:2013-02-15 14:45:44

标签: c# xml winforms serialization

我保存了如下所示的数据,现在我想将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");

1 个答案:

答案 0 :(得分:1)

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; 
} 

UPDATE 如果要保存客户数据更改的历史记录并加载最后一个,请保存并加载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;
}