Thursday, 24 January 2013

XML Serialization in C# 4.5

XML Serialization in C# 4.5


Step 1) Add a class Called Person

    [Serializable]
   public class Person
    {
        public int ID { get; set; }
        public String firstname { get; set; }
        public String lastname { get; set; }
    
    }
Step 2)  Add a method to Serialize Person(s) object to XML

        void XmlSearilize()
        {
            try
            {
                Person p = new Person { ID = 1, firstname = "syam", lastname = "benegal" };

                System.Xml.Serialization.XmlSerializer ser = new XmlSerializer(typeof(Person));
                FileStream fs = new FileStream(@"c:\xml1.xml", FileMode.Create);
                ser.Serialize(fs, p);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
           
        }

Step 3)  Call this Method in Program Entry Point

        public static void Main()
        {
            xmlse xd = new xmlse();
            xd.XmlSearilize();
        }
Step 4) Run the Application

open the file in C:\xml1.xml

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ID>1</ID>
  <firstname>syam</firstname>
  <lastname>benegal</lastname>
</Person>

Example 2


XML Serialize Array of Objects

//Serialize Array of Objects
    void XmlSearilize()
        {
            try
            {


                Person[] persons = new Person[]{
                    new Person { ID = 1, firstname = "syam", lastname = "benegal" },
                    new Person { ID = 2, firstname = "kate", lastname = "winslet" },
                    new Person { ID = 3, firstname = "keter", lastname = "paul" },
                    new Person { ID = 4, firstname = "cat", lastname = "bengal" }

                };
                System.Xml.Serialization.XmlSerializer ser = new XmlSerializer(typeof(Person[]));
                FileStream fs = new FileStream(@"c:\xml1.xml", FileMode.Create);
                ser.Serialize(fs, persons);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
           
        }

output:


<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <ID>1</ID>
    <firstname>kate</firstname>
    <lastname>winslet</lastname>
  </Person>
  <Person>
    <ID>2</ID>
    <firstname>jenny</firstname>
    <lastname>mathew</lastname>
  </Person>
  <Person>
    <ID>3</ID>
    <firstname>keter</firstname>
    <lastname>paul</lastname>
  </Person>
  <Person>
    <ID>4</ID>
    <firstname>cat</firstname>
    <lastname>bengal</lastname>
  </Person>
</ArrayOfPerson>

No comments:

Post a Comment