我有一个包含客户对象的Observable集合:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string Location { get; set; }
public string ZipCode { get; set; }
}
将此文件转储到XML文件的最简单方法是什么,以便稍后阅读?
答案 0 :(得分:10)
XML序列化:
ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
...
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
using (StreamWriter wr = new StreamWriter("customers.xml"))
{
xs.Serialize(wr, customers);
}
要从文件重新加载数据:
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
using (StreamReader rd = new StreamReader("customers.xml"))
{
customers = xs.Deserialize(rd) as ObservableCollection<Customer>;
}