Serializing an object to XML using C#

Hi All, Recently did I work on Serialization of Objects in my project and understood that it was quite easy to do so.. To sum it up , I will just wirte the code in here .

class Program

    {
        static void Main(string[] args)

        {
            Person p = new Person();
            p.FirstName = "Priti";
            p.MI = "h";
            p.LastName = "Desai";
            p.zipcode = 32045;

            //  XmlSerializer class that serializes an object to XML. When you create an   
               instance of  XmlSerializer, you pass the type of the class that you want to
              serialize into its constructor:

            System.Xml.Serialization.XmlSerializer x = new
            System.Xml.Serialization.XmlSerializer(p.GetType());

            //Serialize is overloaded and can send output to a TextWriter, Stream, or    
            XMLWriter object

            StreamWriter writer = new StreamWriter("c:/p.xml");
            x.Serialize(Console.Out, p);
            x.Serialize(writer, p);
            Console.WriteLine();
            Console.ReadLine();
        }

    }

    public class Person

    {
        public string FirstName;
        public string MI;
        public string LastName;
        public int zipcode;
    }

No comments:

Post a Comment