Friday, November 13, 2009

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, 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));
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));

result = (Dictionary)serializer.ReadObject(reader);
reader.Close();

Published 09 November 09 04:08 by Michael Lehman

No comments:

Post a Comment