2

我保存数据如下图,现在我想将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");
4

1 回答 1

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

更新如果要保存客户数据更改的历史记录并加载最后一个,则保存并加载 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;
}
于 2013-02-15T14:51:19.970 回答