Post #7 – Serializing Dictionary<string,string> 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();

Published 09 November 09 04:08 by Michael Lehman

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

Search

This Blog

Syndication

Page view tracker