2

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

4

1 回答 1

14

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>;
}
于 2009-07-28T15:33:21.480 回答