Click here to Skip to main content
15,881,044 members
Articles / Programming Languages / C#

Both XML and Binary Serializable Dictionary

Rate me:
Please Sign up or sign in to vote.
4.67/5 (12 votes)
3 Jan 2011CPOL3 min read 54.5K   1.4K   26  
Created a derived class from Dictionary which is both XML and binary serializable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;

namespace DictionarySerialization
{

    [Serializable]
    [XmlRoot("Dictionary")]
    public class SerializableDictionary<KT, VT>:Dictionary<KT ,VT>,IXmlSerializable
    {

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

        }
        public SerializableDictionary()
        {

        }
        public XmlSchema GetSchema()
        {
            return (null);
        }

        public void ReadXml(XmlReader reader)
        {
            Boolean wasEmpty = reader.IsEmptyElement;

            reader.Read();

            if (wasEmpty)
            {
                return;
            }

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                KT key ;
                if (reader.Name == "Item")
                {
                    reader.Read();
                    Type keytype = Type.GetType(reader.GetAttribute("type"));
                    if (keytype != null)
                    {
                        reader.Read();
                        key = (KT)new XmlSerializer(keytype).Deserialize(reader);
                        reader.ReadEndElement();
                        Type valuetype = (reader.HasAttributes)?Type.GetType(reader.GetAttribute("type")):null;
                        if (valuetype != null)
                        {
                            reader.Read();
                            Add(key, (VT)new XmlSerializer(valuetype).Deserialize(reader));
                            reader.ReadEndElement();
                        }
                        else
                        {
                            Add(key, default(VT));
                            reader.Skip();
                        }
                    }
                    reader.ReadEndElement();

                    reader.MoveToContent();
                }
            }

            reader.ReadEndElement();

        }

        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>
                writer.WriteStartElement("Item");
                //create <key> under <item>
                writer.WriteStartElement("Key");
                writer.WriteAttributeString(string.Empty, "type", string.Empty, key.GetType().AssemblyQualifiedName);
                new XmlSerializer(key.GetType()).Serialize(writer, key);
                //end </key> element               
                writer.WriteEndElement();
                //create <value> under <item>
                writer.WriteStartElement("value");
                if (value != null)
                {
                    writer.WriteAttributeString(string.Empty, "type", string.Empty, value.GetType().AssemblyQualifiedName);
                    new XmlSerializer(value.GetType()).Serialize(writer, value);
                }
                //end </value>  
                writer.WriteEndElement();
                //end </item>
                writer.WriteEndElement();
            }
        }      
       
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer
Bangladesh Bangladesh
Name SYED MD. ABUL BASHAR
Email ID: miltoncse00@gmail.com

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 : http://bd.linkedin.com/in/miltoncse00[^]

My blog :http://ciintelligence.blogspot.com/[^]

Comments and Discussions