XMLSerializable Hashtable
Well its high time that the hash table became XML serializable but i still havent figured out why not.
But while I was thinking about this just thought i'd put it down myself.
I would like to know if there is a more standard implementation for this. But I just managed to this chewing gum class done for now.
using System;
using System.Runtime.Serialization;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
namespace XMLSerializableHashTable
{
[Serializable]
public class SerializableHashtable:Hashtable,
System.Xml.Serialization.IXmlSerializable
{
#region IXmlSerializable Members
#region Node class
/// <summary>
/// This class would be for custom serialization
/// </summary>
[Serializable]
public class Node
{
public Node()
{}
public Node(string k,object v)
{
key = k;
val = v;
}
public string key;
public object val;
}
#endregion Node class for XML Serialization
/// <summary>
/// Write the xml using an array list
/// using the Node to store key value pairs
/// </summary>
/// <param name="writer"></param>
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer xs = new XmlSerializer(typeof(System.Collections.ArrayList),
new System.Type[]{typeof(Node)});
ArrayList list = new ArrayList();
foreach(string key in this.Keys)
{
list.Add(new Node(key,this[key]));
}
xs.Serialize(writer,list);
}
public System.Xml.Schema.XmlSchema GetSchema()
{
// TODO: Add SerializableHashtable.GetSchema implementation
return null;
}
/// <summary>
/// Deserialization using array list
/// and the node(key,value) pairs
/// </summary>
/// <param name="reader"></param>
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer xs = new XmlSerializer(typeof(System.Collections.ArrayList),
new System.Type[]{typeof(Node)});
//Move the reader into the ArrayList element.
reader.Read();
ArrayList list = xs.Deserialize(reader) as ArrayList;
Node node;
if(list == null)
return;
//Reload the hashTable.
for(int i=0;i<list.Count;i++)
{
node = (Node)list[i];
this.Add(node.key,node.val);
}
}
#endregion
}
}