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