Click here to Skip to main content
13,596,105 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


24 bookmarked
Posted 3 Jan 2011
Licenced CPOL

Both XML and Binary Serializable Dictionary

, 3 Jan 2011
Rate this:
Please Sign up or sign in to vote.
Created a derived class from Dictionary which is both XML and binary serializable


Dictionary by default is not XML serializable.To make it XML serializable with XML serializer, we need to implement IXmlSerialiable. But also derived class of Dictionary is not Binary deserializable so here I have given a solution with a Dictionary which is both XML and binary serializable.


DataContractSerializer can serializeDictionary<,> into XML, but we have old code where XML serializer is used and current implementation does not support DataContractSerializer. I needed to use binary serialization for deep copy and also needed XML serialization for other proposes. So I have implemented a dictionary which supports any type of key and value and also can be serialized in XML and also binary format.


For making it serializable, we need to implement a derived class which implements interface IXmlSerializable. Also, to get all functionality of Dictionary, I have implemented that class from Dictionary class. Here both key and value is generic as Dictionary.

 public class SerializableDictionary<KT, VT>:Dictionary<KT ,VT>,IXmlSerializable		

IXmlSerializable class contains the following method that we needed to implement in our class.

public interface IXmlSerializable
    XmlSchema GetSchema();
    void ReadXml(XmlReader reader);
    void WriteXml(XmlWriter writer);

But we also have to make our dictionary binary serializable. For serialization, we need to set serializable attribute over our derived class. However, when we try to deserialize our derived class in raise error saying there is no appropriate contractor to deserialize our class though default constructor exists. Dictionary<> class implements its own custom serialization using ISerializable so our derived class needs special constructor for deserialization.

public SerializableDictionary(SerializationInfo info,
   StreamingContext context):base(info,context)


So now this class is binary serializable. But for XML serialization, we also need to store type of key and value for deserialization. In WriteXml function of IXmlSerializable, we can organize how Dictionary will be converted into XML format. In my code:

public void WriteXml(System.Xml.XmlWriter writer)
           for (int i=0;i<Keys.Count;i++)
               KT key =Keys.ElementAt(i);
               VT value= this.ElementAt(i).Value;
               //create <item>
               //create <key> under <item>
               writer.WriteAttributeString(string.Empty, "type",
       string.Empty, key.GetType().AssemblyQualifiedName);
               new XmlSerializer(key.GetType()).Serialize(writer, key);
               //end </key> element
               //create <value> under <item>
               if (value != null)
                   writer.WriteAttributeString(string.Empty, "type",
           string.Empty, value.GetType().AssemblyQualifiedName);
                   new XmlSerializer(value.GetType()).Serialize(writer, value);
               //end </value>
               //end </item>

In the code, you can see that it first creates an element <Item> for each dictionary item and under which creates <Key> element and also stores type of key of dictionary as attribute. Then it serializes the value of key inside this element. After that, it also stores the <value> element under <item> and also stores type as attribute. As same as key, it also serializes the value part of dictionary. I did not consider null value in my code but thanks to Don Kackman. With his feedback, I have changed my implementation. In that, I again do not allow null in key but in value if value is null then it will not serialize the value and just write in XML like empty element as "<value/>".

We we see the output of SerializableDictionary<int,string> of two elements, then it would look like:

?<?xml version="1.0" encoding="utf-8"?>
      <Key type="System.Int32, mscorlib, Version=, 
	Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <value type="System.String, mscorlib, Version=, Culture=neutral, 
      <Key type="System.Int32, mscorlib, Version=, Culture=neutral, 
      <value type="System.String, mscorlib, Version=, Culture=neutral, 

Now when we deserialize the serialized value of Dictionary<int,string>, then it will use ReadXml of IXmlSerliazable. For deserialization, the first key type is retrieved and after that key is deserialized with the given type. Also value of dictionary is retrieved in the same way. Here as value can be null so for empty value XML element, it returns default value of that type.

public void ReadXml(XmlReader reader)
          Boolean wasEmpty = reader.IsEmptyElement;
          if (wasEmpty)
          while (reader.NodeType != XmlNodeType.EndElement)
              KT key ;
              if (reader.Name == "Item")
                  Type keytype = Type.GetType(reader.GetAttribute("type"));
                  if (keytype != null)
                      key = (KT)new XmlSerializer(keytype).Deserialize(reader);
                      Type valuetype = (reader.HasAttributes)?Type.GetType
                      if (valuetype != null)
                          Add(key, (VT)new XmlSerializer
                          Add(key, default(VT));

I have tested my implementation with both simple and complex types. It could have been possible to have a Dictionary which also contains a property which is also dictionary type. In that case, the WriteXml and ReadXml will also be called again when the dictionary type property needs to be serialized and deseralized.


My implemented Dictionary class supports both XML serializable by XmlSerializer and also supports binary serialization and key and value also support any types. In my attachment, I also have a demo of both generic implementation of both binary deep copy and XML and binary serialization. I have tried to create an complex dictionary implementation and have seen it works well and deserializes into the same values.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
Bangladesh Bangladesh
Email ID:

I am now working as software engineer in Malaysia. I am from Bangladesh and I have completed my B.Sc (Engg.) in CSE from Rajshahi University of Engineering and Technology (RUET).I spend much time in learning latest technology.

My LinkedIn Profile :[^]

My blog :[^]

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
B.Farivar14-Oct-12 20:26
memberB.Farivar14-Oct-12 20:26 
GeneralRe: My vote of 1 Pin
TheQult8-Jul-13 15:37
memberTheQult8-Jul-13 15:37 
QuestionProblem in serializing Pin
n.manish11-Oct-12 23:51
membern.manish11-Oct-12 23:51 
GeneralMy vote of 5 Pin
Bartje66620-Sep-12 1:30
memberBartje66620-Sep-12 1:30 
GeneralMy vote of 5 Pin
lpgray11-Jan-11 3:25
memberlpgray11-Jan-11 3:25 
GeneralMy vote of 5 Pin
Abdul Quader Mamun5-Jan-11 1:08
memberAbdul Quader Mamun5-Jan-11 1:08 
Generalsuggestions to key/value type Pin
Unruled Boy4-Jan-11 0:09
memberUnruled Boy4-Jan-11 0:09 
GeneralRe: suggestions to key/value type Pin
IGood4-Jan-11 8:45
memberIGood4-Jan-11 8:45 
GeneralRe: suggestions to key/value type [modified] Pin
Mr.PoorEnglish4-Jan-11 13:37
memberMr.PoorEnglish4-Jan-11 13:37 
GeneralRe: suggestions to key/value type Pin
Syed BASHAR4-Jan-11 16:26
memberSyed BASHAR4-Jan-11 16:26 
Generalgood timing Pin
Don Kackman3-Jan-11 18:52
memberDon Kackman3-Jan-11 18:52 
GeneralRe: good timing Pin
Syed BASHAR3-Jan-11 20:41
memberSyed BASHAR3-Jan-11 20:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03-2016 | 2.8.180621.3 | Last Updated 4 Jan 2011
Article Copyright 2011 by Syed BASHAR
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid