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.
Here, we have a class called Customer, for customer details.
- class Customer
- {
- public int Id { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Address { get; set; }
- public string Mobile { get; set; }
- public DateTime DOB { get; set; }
- public char Sex { get; set; }
- }
Then, we have a List of Customer details.
- List<Customer> customer = new List<Customer>();
- customer.Add(new Customer { Id = 1, FirstName = "Prakash", LastName = "Kumar", Address = "Thiruvannamali", Mobile = "9940793046", DOB = Convert.ToDateTime("27/04/1990"), Sex = 'M' });
- 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 -
- public List<T> ReadXML<T>(string filename)
- {
- string filePath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/"), "App_Data", filename);
- List<T> result;
- if (!System.IO.File.Exists(filePath))
- {
- return new List<T>();
- }
-
- XmlSerializer ser = new XmlSerializer(typeof(List<T>));
- using (FileStream myFileStream = new FileStream(filePath, FileMode.Open))
- {
- result = (List<T>)ser.Deserialize(myFileStream);
- }
- return result;
- }
Write function -
- public void WriteXML<T>(List<T> list, string filename)
- {
- string filePath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/"), "App_Data", filename);
- XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
- using (TextWriter tw = new StreamWriter(filePath))
- {
- serializer.Serialize(tw, list);
- tw.Close();
- }
- }
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.