The XmlSerializer in .NET has many good qualities. It creates output that is understandable and not overly verbose. It works with many data types. It has a simple, sensible policy -- it only serializes public properties and members. It doesn't require special attributes. The only thing that bothers me is that it doesn't serialize Hashtables or Dictionaries. Here is some code that enables serializing and deserializing those types by using an intermediary List. I haven't tried it using a non-generic ArrayList or array, but I believe that would work too.
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;
public static void Serialize(TextWriter writer, IDictionary dictionary)
{
List<Entry> entries = new List<Entry>(dictionary.Count);
foreach (object key in dictionary.Keys)
{
entries.Add(new Entry(key, dictionary[key]));
}
XmlSerializer serializer = new XmlSerializer(typeof(List<Entry>));
serializer.Serialize(writer, entries);
}
public static void Deserialize(TextReader reader, IDictionary dictionary)
{
dictionary.Clear();
XmlSerializer serializer = new XmlSerializer(typeof(List<Entry>));
List<Entry> list = (List<Entry>)serializer.Deserialize(reader);
foreach (Entry entry in list)
{
dictionary[entry.Key] = entry.Value;
}
}
public class Entry
{
public object Key;
public object Value;
public Entry() {}
public Entry(object key, object value)
{
Key = key;
Value = value;
}
}
It generates output like the following, when the keys and values are strings.
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Entry>
<Key xsi:type="xsd:string">MyKey</Key>
<Value xsi:type="xsd:string">MyValue</Value>
</Entry>
<Entry>
<Key xsi:type="xsd:string">MyOtherKey</Key>
<Value xsi:type="xsd:string">MyOtherValue</Value>
</Entry>
</ArrayOfEntry>
[http://blogs.msdn.com/psheill/archive/2005/04/09/406823.aspx]