NetInverse Developers Blog

January 5, 2010
Category: .Net — Tags: , , , , , — admin @ 9:59 pm

If you use WCF to create web services, you need to define your data contracts by using DataContract/DataMember attributes.
Actually you can use them directly for serialization/deserialization in your code. Following is a sample of how to use DataContract/DataMember attributes for fast object Xml serialization and deserialization.

using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace DataContractSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student()
            {
                Age = 12,
                Name = "David"
            };

            DataContractSerializer dcs = new DataContractSerializer(typeof(Student));
            StringBuilder sb = new StringBuilder();

            using(XmlWriter writer = XmlWriter.Create(sb))
            {
                dcs.WriteObject(writer, student);
            }
            string xml = sb.ToString();

            using (XmlTextReader reader = new XmlTextReader(new StringReader(xml)))
            {
                Student newStudent = (Student) dcs.ReadObject(reader, true);
            }
        }
    }

    [DataContract(Namespace="http://www.netinverse.com")]
    public class Student
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age { get; set; }
    }
}

©2009 NetInverse. All rights reserved. Powered by WordPress