Read And Write Dynamic T Object Into XML File

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 { getset; }  
  4.        public string FirstName { getset; }  
  5.        public string LastName { getset; }  
  6.        public string Address { getset; }  
  7.        public string Mobile { getset; }  
  8.        public DateTime DOB { getset; }  
  9.        public char Sex { getset; }  
  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.   
  10.     XmlSerializer ser = new XmlSerializer(typeof(List<T>));  
  11.     using (FileStream myFileStream = new FileStream(filePath, FileMode.Open))  
  12.     {  
  13.         result = (List<T>)ser.Deserialize(myFileStream);  
  14.     }  
  15.     return result;  
  16. }  

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.