How to Serialize Object to XML in C#

12 Apr 2014, 02:40 AM

In .net framework XmlSerializer class is used to serialize and de serialize object. Create the instance of the XmlSerializer() class and pass the type of the object as parameter. Call the Serialize method to get the XML

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

writer is the instance of the XmlWriter class and Serialize methods write the final xml in the stream writer.

  Student value = new Student();
  value.StudentId = 2;
  value.Name = "Test User";

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

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

  var xmlToReturn = stringWriter.ToString();


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
Expalins How to serialize object to xml using c#

Date Posted 12 Apr 2014, 02:34 AM
Author Brainy Solutions
Views 2,500