Generic methods to serialize or Deserialize XML

When you are working with XML files and C# Objects then you know about this serialization and deserialization thing. so today I'm not going to talk about the theory stuff regarding those concepts, rather than that I'm going to show you how to serialize or deserialize any given object or XML file using generic method. Happy coding.... and have a nice day...!




     /// <summary>  
     /// Serialize object to XML File  
     /// </summary>  
     /// <typeparam name="T">Object Type</typeparam>  
     /// <param name="value">Object contain Data</param>  
     /// <param name="filename">XML File name and Path </param>  
     public void Serialize<T>(T value,string filename)  
     {  
   
       try  
       {  
         XmlSerializer xmlserializer = new XmlSerializer(typeof(T));  
         Stream stream = new FileStream(filename, FileMode.Create);  
         xmlserializer.Serialize(stream, value);  
         stream.Close();  
       }  
       catch (Exception ex)  
       {  
         throw new Exception("Error Message");  
       }  
     }  
   
     /// <summary>  
     /// Deserialize XML File to a given object  
     /// </summary>  
     /// <typeparam name="T">Type of the Object</typeparam>  
     /// <param name="filename">Xml File name and File Path</param>  
     /// <returns>T Object with data</returns>  
     public T Deserialize<T>(String filename)  
     {  
       try  
       {  
         XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));  
         Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);  
         var result = (T)xmlSerializer.Deserialize(stream);  
         stream.Close();  
         return result;  
       }  
       catch (Exception ex)  
       {  
         return default(T);  
       }  
     }  

Comments

Popular posts from this blog

Deep dive into OpenXML Part 1

Deep dive into OpenXML Part 2

Convert XML data to dynamic (ExpandoObject) Object