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

时间:2022-06-28 19:55:23

I've have an Observable collection containing customer objects:

我有一个包含客户对象的可观察集合:

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

What is the easiest way to dump this out to an XML file so I can read it in later?

将其转储到XML文件的最简单方法是什么,这样我可以在以后阅读它?

1 个解决方案

#1


10  

XML serialization :

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

To reload the data from the file :

从文件中重新加载数据:

XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
using (StreamReader rd = new StreamReader("customers.xml"))
{
    customers = xs.Deserialize(rd) as ObservableCollection<Customer>;
}

#1


10  

XML serialization :

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

To reload the data from the file :

从文件中重新加载数据:

XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
using (StreamReader rd = new StreamReader("customers.xml"))
{
    customers = xs.Deserialize(rd) as ObservableCollection<Customer>;
}