将Observable对象集合保存到XML文件的最简单方法是什么?

时间:2009-07-28 15:30:57

标签: c# xml observablecollection

我有一个包含客户对象的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文件的最简单方法是什么,以便稍后阅读?

1 个答案:

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