Write / Create XML file based on Model:
Below code will generate XML file from Model(here Customer model) using XMLSerializer:
//Write XML based on Customer Model
System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(List<Customer>));
//HardCoded Path, You can create file at application path
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Product.xml";
System.IO.FileStream fileObj;
try
{
fileObj= System.IO.File.Create(path);
writer.Serialize(fileObj, customerList);
fileObj.Close();
}
catch(Exception ex)
{
throw new ApplicationException("Something went wrong in XML Generation:" + ex.Message);
//Some logic for error Logging
}Read XML file data into Model:Below code read XML file into Model(here Customer model) using XMLSerializer:
//Read XML in Customer Model
System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(List<Customer>));
System.IO.StreamReader fileReader;
List<Customer> customersList=new List<Customer>();
try
{
fileReader = new System.IO.StreamReader(path);
customersList = (List<Customer>)reader.Deserialize(fileReader);
fileReader.Close();
}
catch (Exception ex)
{
throw new ApplicationException("Something went wrong in XML Generation:" + ex.Message);
//Some logic for error Logging
}