Rakesh Rajan's blog

Thoughts on .NET, software and a few trivial things...

XML Serialize IDictionary types (Hashtable, DictionaryBase etc.)

Problem

You want to serialize a type; however it:

  • implements IDictionary, or
  • derives from DictionaryBase, contains a member which implements IDictionary or derives from DictionaryBase,
which causes XmlSerializer to throw an exception:
"System.NotSupportedException: The type X is not supported because it implements IDictionary".

Solution

Override XmlSerialization by making the type implement the System.Xml.Serialization.IXmlSerializable class. Define how you want the object to be serialized in XML in the WriteXml method, and define how you could recreate the object from an xml string in the ReadXml method.

Code

Download the full code here.

The WriteXml and ReadXml methods used in the sample follow.

public void WriteXml(System.Xml.XmlWriter writer)
{
	// Used while Serialization

	// Serialize each BizEntity this collection holds
	foreach( string key in this.Dictionary.Keys )
	{
		Serializer.Serialize(writer, this.Dictionary[key]);
	}
}

public void ReadXml(System.Xml.XmlReader reader)
{
	// Used while Deserialization

	// Move past container
	reader.Read();

	// Deserialize and add the BizEntitiy objects
	while( reader.NodeType != XmlNodeType.EndElement )
	{
		BizEntity entity;

		entity = Serializer.Deserialize(reader) as BizEntity;
		reader.MoveToContent();
		this.Dictionary.Add(entity.Key, entity);
	}
}

Description

By default, XML Serialization does not serialize types that implement IDictionary; it throws an exception when you attempt to do so. This comes quite in the way when you need to switch serialization techniques, or have custom collections which derive from DictionaryBase or any other sort of scenario.

The workaround for this problem is to let XML Serializer know how to serialize your IDictionary types yourself, by implementing the System.Xml.Serialization.IXmlSerializable class. This interface declares three methods - ReadXml, WriteXml and GetSchema.

When XmlSerializer attempts to serialize a type and finds that it implements IXmlSerializable, the serializer would simply pass control to the ReadXml (during deserialization) or WriteXml (during serialization) methods. In other words, you yourself handle how serialization and deserialization should happen.

Posted: Jan 15 2006, 12:42 PM by rakeshrajan | with no comments
Filed under:
Leave a Comment

(required) 

(required) 

(optional)

(required)