XmlSerializer won't serialize objects that implement IDictionary by default.
One way around this is to write a new class that wraps an IDictionary object and copies the values into an array of serializable objects.
So you can write a class like that :
public class DictionarySerializer : IXmlSerializable
{
const string NS = "http://www.develop.com/xml/serialization";
public IDictionary dictionary;
public DictionarySerializer()
{
dictionary = new Hashtable();
}
public DictionarySerializer(IDictionary dictionary)
{
this.dictionary = dictionary;
}
public void WriteXml(XmlWriter w)
{
w.WriteStartElement("dictionary", NS);
foreach (object key in dictionary.Keys)
{
object value = dictionary[key];
w.WriteStartElement("item", NS);
w.WriteElementString("key", NS, key.ToString());
w.WriteElementString("value", NS, value.ToString());
w.WriteEndElement();
}
w.WriteEndElement();
}
public void ReadXml(XmlReader r)
{
r.Read(); // move past container
r.ReadStartElement("dictionary");
while (r.NodeType != XmlNodeType.EndElement)
{
r.ReadStartElement("item", NS);
string key = r.ReadElementString("key", NS);
string value = r.ReadElementString("value", NS);
r.ReadEndElement();
r.MoveToContent();
dictionary.Add(key, value);
}
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return LoadSchema();
}
}
You then create your webservice method with this return type.
[WebMethod]
public DictionarySerializer GetHashTable()
{
Hashtable ht = new Hashtable();
ht.Add(1, "Aaron");
ht.Add(2, "Monica");
ht.Add(3, "Michelle");
return new DictionarySerializer (h1);
}
If you need more information, the paper contain some information about this technic.