In this write-up, I will demonstrate a simple example for reading and writing a List<T> object into XML file, using XML Serialization in C# application.



H
ere, we have a class called Customer, for customer details.

  1. class Customer
  2. {
  3. public int Id { get; set; }
  4. public string FirstName { get; set; }
  5. public string LastName { get; set; }
  6. public string Address { get; set; }
  7. public string Mobile { get; set; }
  8. public DateTime DOB { get; set; }
  9. public char Sex { get; set; }
  10. }

Then, we have a List of Customer details.

  1. List<Customer> customer = new List<Customer>();
  2. customer.Add(new Customer { Id = 1, FirstName = "Prakash", LastName = "Kumar", Address = "Thiruvannamali", Mobile = "9940793046", DOB = Convert.ToDateTime("27/04/1990"), Sex = 'M' });
  3. customer.Add(new Customer { Id = 1, FirstName = "Murali", LastName = "Pichandi", Address = "Thiruvannamali", Mobile = "9940793046", DOB = Convert.ToDateTime("15/05/1989"), Sex = 'M' });

To read and write an XML file using XML Serialization, I have declared two parameters - list of T class and filename as a parameter,

The following functions will specify the reading and writing the XML files using the XML Serialization.

Read function -

  1. public List<T> ReadXML<T>(string filename)
  2. {
  3. string filePath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/"), "App_Data", filename);
  4. List<T> result;
  5. if (!System.IO.File.Exists(filePath))
  6. {
  7. return new List<T>();
  8. }
  9. XmlSerializer ser = new XmlSerializer(typeof(List<T>));
  10. using (FileStream myFileStream = new FileStream(filePath, FileMode.Open))
  11. {
  12. result = (List<T>)ser.Deserialize(myFileStream);
  13. }
  14. return result;
  15. }

Write function -

  1. public void WriteXML<T>(List<T> list, string filename)
  2. {
  3. string filePath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/"), "App_Data", filename);
  4. XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
  5. using (TextWriter tw = new StreamWriter(filePath))
  6. {
  7. serializer.Serialize(tw, list);
  8. tw.Close();
  9. }
  10. }

The above functions are used for reading and writing a dynamic <T> object into an XML file.

Now, we are able to read and write a dynamic list of classes into an XML file, using the Serialization method.