C# XML Serialization

Here is a simple example on how to serialized objects to XML in C#.

Additional, here are some related MSDN Articles.

How to serialize an object to XML by using Visual C#
http://support.microsoft.com/kb/815813

?: Operator (C# Reference)
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx

using System;

namespace XML_Serial
{
    public class Employee
    {
        public Int32 ID { set; get; }
        public string firstName { set; get; }
        public string lastName { set; get; }

        public Employee() 
        {
            this.ID = -1;
            this.firstName = null;
            this.lastName = null;
        }

        public Employee(Int32 ID, string firstName, string lastName) 
        {
            /* Tenary Operator: this.ID = ID > 0 ? ID : -1; 
                Is the same as:
                    if( ID > 0)
                        this.ID = ID
                    else
                        this.ID = -1
             */
            this.ID = ID > 0 ? ID : -1;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        private System.Xml.Serialization.XmlSerializer getSerializer()
        {
            return (new System.Xml.Serialization.XmlSerializer(this.GetType()));
        }

        public void serializedPrint() 
        {
            System.Xml.Serialization.XmlSerializer serializer = this.getSerializer();
            serializer.Serialize(Console.Out, this);  
        }
    }

    class Run
    {
        static void Main(string[] args)
        {
            //- Normal Input Test-----------------------------
            Employee emp0 = new Employee(1, "Bit", "Diddler");
            emp0.serializedPrint();

            /* Sample Output: emp0
<?xml version="1.0" encoding="IBM437"?>
    <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <ID>1</ID>
        <firstName>Bit</firstName>
        <lastName>Diddler</lastName>
    </Employee>
             */

            //- Tenary Test------------------------------------
            Employee emp1 = new Employee(-1111, "Dan", "Moore");
            emp1.serializedPrint();

            /* Sample Output: emp1
<?xml version="1.0" encoding="IBM437"?>
    <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <ID>-1</ID>
        <firstName>Dan</firstName>
        <lastName>Moore</lastName>
    </Employee>
             */
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s