What is Xml Serialization

Lets first understand Serialization.
Serialization is the process of converting an object into a format that can be transferred over the network.

So, What is Xml Serialization?

XML Serialization is the process of converting an object into XML file which is easy to read and portable over network using a protocol such as HTTP.

How we can do Xml Serialization ? Lets understand this by writing C# code.

Create a Console Application Project in Visual Studio.

Add a class with any name, in this example I have named this class as XmlSerialize

See below code snippet.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApplicationDemo
{
   public class XmlSerialize
    {
        
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public int Stock { get; set; }

        public void Save(string filename)
        {
            using (var fileStream = new FileStream(filename,FileMode.Create))
            {
                var xmlFile = new XmlSerializer(typeof(XmlSerialize));
                xmlFile.Serialize(fileStream, this);
            }
        }
    }

}


Write Below code in Program.cs

static void Main(string[] args)
        {
            XmlSerialize objXMLSerialize = new XmlSerialize();
            objXMLSerialize.ProductID = 10001;
            objXMLSerialize.ProductName = "Laptop";
            objXMLSerialize.Stock = 50;
            objXMLSerialize.Save("Product.xml");
           
        }

Run this code and you may see Product.xml file in bin -> Debug(or Release) folder.

<?xml version="1.0"?>
<XmlSerialize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ProductID>10001</ProductID>
  <ProductName>Laptop</ProductName>
  <Stock>50</Stock>
</XmlSerialize> 

If you want an attribute in XML

For eg you want to display ProductID as attribute, then add below attribute in .CS file

 [XmlAttribute]

So code will look like:

 [XmlAttribute]
 public int ProductID { get; set; }

After successful execution, newly created xml file will contain below lines
<?xml version="1.0"?>
<XmlSerialize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ProductID="10001">
  <ProductName>Laptop</ProductName>
  <Stock>50</Stock>
</XmlSerialize>

You may notice that ProductID is displaying as an attribute in above xml file.

Hope you understand the meaning of Xml Serialization and how to implement Xml Serialization  in C#.

Happy Coding :)

Comments

Popular posts from this blog

CAML Query in SharePoint 2010

Calling REST APi from server side code - C#

All about SharePoint 2010 Content Type Hub

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX