Serializing Lists of Classes to XML

So some times we want to convert object to xml. We can follow severel cumbersome methods. So I am using Utlity methods to convert c# object to xml and xml to c# object.

Suppose we have class like below

public class Student
 public int Id { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }

And we want serialize List<Student> to xml. So we can use this utlity function

/// <summary>
/// Serialize object to xml
/// </summary>
/// <typeparam name="T">Object type</typeparam>
/// <param name="obj">Object</param>
/// <returns>XML</returns>
public static string ToXml<T>(T obj)
using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture))
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stringWriter, obj);
return stringWriter.ToString();

As a example we populate List<student>  with dummy data

 List <Student> studentList = new List<Student>();

studentList.Add(new Student {
 FirstName = "jeevan",
 LastName = "JLast name",
 Id = 1

studentList.Add(new Student
 FirstName = "john",
 LastName = "johnLast name",
 Id = 2

Then call out utility function

string xml = Utility.ToXml(studentList);

then out xml variable look like as below

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfStudent xmlns:xsi="" xmlns:xsd="">
<LastName>JLast name</LastName>
<LastName>johnLast name</LastName>



I am a passionate software developer. I develop software using microsoft technologies and other trending web technologies. currently works at sitecore as a developer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s