Post #7 – Serializing Dictionary to/from XML

I spent a bit of time searching for the magic of how to use XmlSerialize with the Dictionary type this morning and thought I’d share the easy-to-use result:

Assuming you have an object, let’s say it’s called “data” that is of type Dictionary<string,string>, you can save it to an XML file whose name is contained in the string “dataName” like this:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(dataName, settings);
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string,string>));
serializer.WriteObject(writer, data);
writer.Close();

(XmlWriterSettings is used to cause the resulting XML come out on human-readable multiple lines instead of all on one very long line.)

and read it back like this:

XmlReader reader = XmlReader.Create(dataName);
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string,string>));

result = (Dictionary<string,string>)serializer.ReadObject(reader);
reader.Close();