Deserialize and Serialize a xml using DatacontractSerializer

I have finally decided to create my blog about programming and technology in general,I hope this blog will be useful for those who can read these lines.

I will begin for something simple, how we can serialize or deserialize a xml file using  DataContractSerializer. The .Net framework release 3.5  included a new serialization engine called DataContractSerializer, this class is the replacement of the old XMLSerializer.

In order to use this class we will need to specify that classes will be serialized using the attribute Datacontract and what properties of that class will be included in the process of serialization using the attribute Datamember.

Imagine that we need to create the configuration of a menu that looks like the following xml:

<SecurityConfiguration xmlns:i=””””&gt;






<Title>New Order</Title>












To make this xml we will need to create the following classes:

Security Configuration Class

[DataContract(Name = &quot;SecurityConfiguration&quot;, Namespace = &quot;&quot;)]
    public class SecurityConfiguration
        [DataMember(Name = &quot;MenuGroups&quot;, Order = 0)]
        public List&lt;MenuGroup&gt; MenuGroups { get; set; }

        public SecurityConfiguration()
            MenuGroups = new List&lt;MenuGroup&gt;();

Menu Group Class

 [DataContract(Name = &quot;Group&quot;, Namespace = &quot;&quot;)]
    public class MenuGroup
        [DataMember(Order = 0)]
        public string Name { get; set; }

        [DataMember(Name = &quot;MenuEntries&quot;, Order = 1)]
        public List&lt;MenuEntry&gt; MenuEntries { get; set; }

        public MenuGroup()
            MenuEntries = new List&lt;MenuEntry&gt;();


Menu Entry Class

[DataContract(Name = &quot;MenuEntry&quot;, Namespace = &quot;&quot;)]
    public class MenuEntry

        [DataMember(Order = 0)]
        public string Title { get; set; }

        [DataMember(Order = 1)]
        public string Link { get; set; }

        [DataMember(Order = 2)]
        public AllowedGroupsList AllowedGroups { get; set; }

        public MenuEntry()
            AllowedGroups = new AllowedGroupsList();

Allowed Groups List Class

[CollectionDataContract(Name = &quot;AllowedGroups&quot;, ItemName = &quot;Group&quot;, Namespace = &quot;&quot;)]
    public class AllowedGroupsList : List&lt;string&gt;;

To have full control on class serialization with DataContractSerializer, you should mark class with [DataContract] and every property, which will be serialized with [DataMember]. If you mark class with [DataContract] only, none of properties will be serialized.

Another important thing to know is that DataContractSerializer expects things to be in alphabetical order. You need to add Order to your Data Members if you want serialize/deserialize the properties in a particular order.

Now we need to create an instance of the Security Configuration like this:

var configuration = new SecurityConfiguration()
                MenuGroups = new List&lt;MenuGroup&gt;()
                    new MenuGroup()
                        Name = &quot;Orders&quot;,
                        MenuEntries = new List&lt;MenuEntry&gt;()
                            new MenuEntry()
                                Title = &quot;New Order&quot;,
                                Link = &quot;/NewOrder&quot;,
                                AllowedGroups = new AllowedGroupsList()

To Serialize the object using the DataContractSerializer class we do the following :

var serializer = new DataContractSerializer(typeof(SecurityConfiguration));
            var memoryStream = new MemoryStream();
            serializer.WriteObject(memoryStream, configuration);
            memoryStream.Position = 0;
            string xmlString;
            using (var reader = new StreamReader(memoryStream))
                xmlString = reader.ReadToEnd();

In the case that we need to deserialize the xml file we can do it like this:

	 var serializer = new DataContractSerializer(typeof(SecurityConfiguration));
            var memoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(@&quot;..\..\SecurityConfiguration.xml&quot;));
            var configuration = serializer.ReadObject(memoryStream) as SecurityConfiguration;

I hope the with this short tutorial about how to use the DatacontractSerailizer will be useful for you guys. The DataContractSerializer is very easy to use for creating objects for file settings or to serialize xml data to pass it over the network. The data types supported for this class you can find them here

The code of this post is in my Github.




This entry was posted in .Net and tagged , , , . Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s