Aug 14, 2013

How to Serialize a custom object list in XML using c#?

To serialize a custom list into XML I just created one extension method "WriteXML".
It will serialize any type of List object. You can see in the example it's taking a generic List of objects.

public static class MyExtensionMethods
{
    public static string WriteXML<TSource>(this List<TSource> source)
    {
        StringBuilder sb = new StringBuilder();
        XmlSerializer x = new XmlSerializer(source.GetType());
        var sw = new StringWriterUtf8(sb);
        x.Serialize(sw, source);
        return sw.ToString();
    }
}

Example:-
public class Employee
{
    [XmlIgnore] // If you don't want to serialize some property then provide [XmlIgnore] attribute before that property.
    public string EmployeeID { get; set; }
    public string EmployeeName { get; set; }
    [XmlElement(ElementName = "Address")] // while serialization if you want to change the Element name the use this attribute.
    public string AddressLine1 { get; set; }
}

public class EmployeeController
{
    public void SerializeList()
    {
        List<Employee> employeeList = new List<Employee>();
        // Just Adding some data to the Employee list.
        employeeList.Add({ EmployeeID = 1, EmployeeName = "Jon", AddressLine1 = "Some Address1" });
        employeeList.Add({ EmployeeID = 2, EmployeeName = "David", AddressLine1 = "Some Address2" });
       
        // In xmlStr you will find the serialized string.
        string xmlStr = employeeList.WriteXML<Employee>();
       
        // Now I want to save this XML into excel.
        string fileName = DateTime.Now.ToShortDateString() + "_EmployeeList.xls";
        Download(xmlStr, fileName);
    }
   
    public void Download(string xmlString, string fileName)
    {   
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.ContentType = "application/vnd.ms-excel";
        Response.Write(xmlString);
        Response.End();
    }
}

No comments: