How to Write Generic Method to Serialize object to XML in C#

12 Apr 2014, 02:56 AM

Generic is very powerful concept in C#. it is very simple to write the generic XML serializer in .Net framework. See the code below to write generic XML serialize method.

 public static string Serialize<T>(T value)
 {
            
     var xmlToReturn = "";
     if (value != null)
     {
         try
         {

             var stringWriter = new StringWriter();
             var writer = XmlWriter.Create(stringWriter);


             var xmlSerializer = new XmlSerializer(value.GetType());
             xmlSerializer.Serialize(writer, value);

             xmlToReturn = stringWriter.ToString();

             writer.Close();

          }
          catch (Exception ex)
          {
          }
      }
      
      return xmlToReturn;
 }

Related Contents

15 May 2014, 08:07 AM
C#, LINQ, List
15 May 2014, 07:54 AM
C#, LINQ, List
29 Apr 2014, 03:07 AM
C#, Generic
About
Write a generic method to serialize object to XML

Date Posted 12 Apr 2014, 02:43 AM
Author Brainy Solutions
Views 1,426
;