Web API Code to Generate XML from Model and Read XML File into Model

Write / Create XML file based on Model:
 
Below code will generate XML file from Model(here Customer model) using XMLSerializer:  
  1. //Write XML based on Customer Model  
  2. System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(List<Customer>));  
  3. //HardCoded Path, You can create file at application path  
  4. var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Product.xml";  
  5. System.IO.FileStream fileObj;   
  6.   
  7. try  
  8. {   
  9.     fileObj= System.IO.File.Create(path);  
  10.     writer.Serialize(fileObj, customerList);  
  11.     fileObj.Close();  
  12.  }  
  13. catch(Exception ex)  
  14. {  
  15.     throw new ApplicationException("Something went wrong in XML Generation:" + ex.Message);  
  16.     //Some logic for error Logging  
  17.       
  18. }  
Read XML file data into Model:

Below code read XML file into Model(here Customer model) using XMLSerializer:   
  1. //Read XML in Customer Model  
  2. System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(List<Customer>));  
  3. System.IO.StreamReader fileReader;  
  4. List<Customer> customersList=new List<Customer>();  
  5.   
  6. try  
  7. {  
  8.     fileReader = new System.IO.StreamReader(path);  
  9.     customersList = (List<Customer>)reader.Deserialize(fileReader);  
  10.     fileReader.Close();  
  11. }  
  12. catch (Exception ex)  
  13. {  
  14.     throw new ApplicationException("Something went wrong in XML Generation:" + ex.Message);  
  15.     //Some logic for error Logging  
  16.