Xml Serialization and Deserialization in C#.net Example

What is XML Serialization?

Converting a .Net object to a XML object is know as XML serialization and vice versa is known as XML deserialization.


Just follow the below code and do the changes as per your requirement.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace XML_Serilization_and_Deserilization
{
    class Program
    {
        static void Main(string[] args)
        {
            //Xml Serialization
            Teacher[] teachers =new Teacher[2]{
                new Teacher() { TeacherId=1,Teachername="T1"},
                new Teacher() { TeacherId = 2, Teachername = "T2" } };

            School obj = new School() { SchoolName = "School1", SchoolAddress = "India", ZipCode = 12344,Teachers=teachers };
            XmlSerializer serObj = new XmlSerializer(typeof(School));
            StreamWriter write = new StreamWriter(@"D:\Users\aj\Desktop\Test\School.xml");
            serObj.Serialize(write, obj);
            write.Close();
            //Xml Deserialize
            StreamReader rdr = new StreamReader(@"D:\Users\aj\Desktop\Test\School.xml");
            School DeserilizedObj= (School)serObj.Deserialize(rdr);
        }
    }
    public class School
    {
        public string SchoolName { get; set; }
        public string SchoolAddress { get; set; }
        public int ZipCode { get; set; }
        public Teacher[] Teachers { get; set; }
    }
    public class Teacher
    {
        public int TeacherId { get; set; }
        public string Teachername { get; set; }
    }
}



1 comment:

Unknown said...

thank you so much made it very easy for serializing xml

Post a Comment

Popular Posts