简体   繁体   中英

What is the easiest way to save an Observable collectin of object to an XML file?

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 serialization :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM