Generic Serializing and Deserializing Object as XML Data Using XmlSerializer

Introduction

Here are the steps to serialize and deserialize an object as XML data.

Serialization: Converts Object to XML

DeSerialization: Converts XML to Object

Step 1: Used Namespaces:

using System;

using System.IO;

using System.Collections.Generic;

using System.Xml;

using System.Xml.Serialization;

 

Step 2: Usage:

SerilizeList();
DeSerilizeList();

 

Step 3: Used List for Demo:

public
List<Product> GetProductList()
{

     List<Product> list = new List<Product>();

 

     Product product = new Product(new Section[3]);

     product.Sections[0] = new Section("1", new Header[3]);

     product.Sections[0].Headers[0] = new Header("P1", "C1", "T1");

     product.Sections[0].Headers[1] = new Header("P2", "C2", "T2");

 

     product.Sections[1] = new Section("2", new Header[3]);

     product.Sections[1].Headers[0] = new Header("P1", "C1", "T1");

     product.Sections[1].Headers[1] = new Header("P2", "C2", "T2");

 

     list.Add(product);

     return list;

}

Step 4: Serializing the List<T> to XML:

//Serializing the List

public void SerilizeList()
{
     //Creating Custom List
     List
<Product> list = GetProductList();
     Serialize<Product>(list);
}

//Generic serialize

private void Serialize<T>(List<Product> list)

{

     //Creating XmlSerializer.

     XmlSerializer serializer = new XmlSerializer(typeof(List<T>));

     //Creating text writer for xml data

     TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));

     //Convert the XML to List

     serializer.Serialize(tw, list);

     tw.Close();
}

Step 5: Output of Serializing:

<?xml version="1.0" encoding="utf-8"?>

<ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Product>

    <Sections>

      <Section Name="1">

        <Headers>

          <Header PropertyName="P1" ClassName="C1">T1</Header>

          <Header PropertyName="P2" ClassName="C2">T2</Header>

          <Header xsi:nil="true" />

        </Headers>

      </Section>

      <Section Name="2">

        <Headers>

          <Header PropertyName="P1" ClassName="C1">T1</Header>

          <Header PropertyName="P2" ClassName="C2">T2</Header>

          <Header xsi:nil="true" />

        </Headers>

      </Section>

      <Section xsi:nil="true" />

    </Sections>

  </Product>

</ArrayOfProduct>

Step 6: Deserializing the XML to List<T>:

//Serializing the List

public
void DeSerilizeList()
{
     //Getting the DeSerialized list of product.

     List
<Product> b = GenericDeSerialize<Product>();

//Displays the results

foreach (Product product in b)

{

     Response.Write(product.Sections[0].Name + ",");

     Response.Write(product.Sections[1].Name);

 }

}

//Deserialize
public List<T> GenericDeSerialize<T>()
{

     //Creating XmlSerializer for the object

 XmlSerializer serializer = new XmlSerializer(typeof(List<T>));

 

 //Geting XMl from the file.

 TextReader tr = new StreamReader(Server.MapPath("book1.xml"));

 

//Deserialize back to object from XML

List<T> b = (List<T>)serializer.Deserialize(tr);

tr.Close();

      return b;
}

Step 7: Output of Deserialize:

1.jpg

Step 8: List has no collection:

<?xml version="1.0" encoding="utf-8"?>

<ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Product />

</ArrayOfProduct>

Step 9: Copy and paste the following code snippet:

using System.Xml;

using System.Xml.Serialization;

 

namespace SampleApplication

{

    public partial class SerializeMe : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            SerilizeList();

            DeSerilizeList();

        }

        //Serializing the List

        public void SerilizeList()

        {

            //Creating Custom List

            List<Product> list = GetProductList();

            Serialize<Product>(list);

        }

 

        //Generic serialize

        private void Serialize<T>(List<Product> list)

        {

            //Creating XmlSerializer.

            XmlSerializer serializer = new XmlSerializer(typeof(List<T>));

            //Creating text writer for xml data

            TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));

            //Convert the XML to List

            serializer.Serialize(tw, list);

            tw.Close();

        }

 

        //Serializing the List

        public void DeSerilizeList()

        {

            //Getting the DeSerialized list of product.

            List<Product> b = GenericDeSerialize<Product>();

 

            //Displays the results

            foreach (Product product in b)

            {

                Response.Write(product.Sections[0].Name + ",");

                Response.Write(product.Sections[1].Name);

            }

        }

 

        //Deserialize

        public List<T> GenericDeSerialize<T>()

        {

            //Creating XmlSerializer for the object

            XmlSerializer serializer = new XmlSerializer(typeof(List<T>)); 

            //Geting XMl from the file.

            TextReader tr = new StreamReader(Server.MapPath("book1.xml")); 

            //Deserialize back to object from XML

            List<T> b = (List<T>)serializer.Deserialize(tr);

            tr.Close();

            return b;

        }

        public List<Product> GetProductList()

        {

            List<Product> list = new List<Product>();

 

            Product product = new Product(new Section[3]);

            product.Sections[0] = new Section("1", new Header[3]);

            product.Sections[0].Headers[0] = new Header("P1", "C1", "T1");

            product.Sections[0].Headers[1] = new Header("P2", "C2", "T2");

 

            product.Sections[1] = new Section("2", new Header[3]);

            product.Sections[1].Headers[0] = new Header("P1", "C1", "T1");

            product.Sections[1].Headers[1] = new Header("P2", "C2", "T2");

 

            list.Add(product);

            return list;

        }
}

Used Class For Demo:

public class Product

    {

        public Product()

        {

        }

        public Product(Section[] sections)

        {

            this.Sections = sections;

        } 

        public Section[] Sections;

    } 

    public class Section

    {

        public Section()

        {

        } 

        public Section(string name, Header[] headers)

        {

            this.Name = name;

            this.Headers = headers;

        } 

        [XmlAttribute]

        public string Name;

        public Header[] Headers;

    } 

    public class Header

    {

        public Header()

        {

        }

        public Header(string propertyName, string className, string text)

        {

            this.PropertyName = propertyName;

            this.ClassName = className;

            this.Text = text;

        } 

        [XmlAttribute]

        public string PropertyName; 

        [XmlAttribute]

        public string ClassName; 

        [XmlText]

        public string Text;

    }
}

Thanks for reading this article. Have a nice day.

Up Next
    Ebook Download
    View all
    Learn
    View all