C# tip: an easy way to store and load a Dictionary object into and from XML

Posted: (EET/GMT+2)

 

Among with the generic List<T> class, the Dictionary<TKey, TValue> class is one of the most-used collection classes in the C# code I write. Now, I lately needed a quick way to store a Dictionary object into an XML file, and the good news is that with a little bit of LINQ magic, this turns out to be a three-liner.

Similarly, loading that Dictionary object from an XML file is easy, as the following code shows. Let's first take a simple initialization:

Dictionary data = new Dictionary();
data.Add("Key1", "Data1");
data.Add("Key2", "Data2");
data.Add("Key3", "Data3");

Next, let's write a simple method to save such a dictionary to an XML file on disk:

using System.Linq;
using System.Xml.Linq;

...
internal static void SaveDictionary(Dictionary data, string filename)
{
  // create the xml data
  XElement xml = new XElement("MyData",
    data.Select(d => new XElement(d.Key, d.Value)));

  // save it to a file, overwriting existing file if needed
  xml.Save(filename);
}

Notice how here the XElement class from the System.Xml.Linq is used to create the XML data. The list if XML elements is created by calling the Select LINQ extension method on all the items in the dictionary, and this list is passed to the XElement constructor, which in turn is able to create the final XML elements.

To call the method, you'd simply say something like this:

SaveDictionary(data, @"C:\Temp\Data.xml");

After which you'd get an XML file saved, with contents like this:

<?xml version="1.0" encoding="utf-8"?>
<MyData>
  <Key1>Data1</Key1>
  <Key2>Data2</Key2>
  <Key3>Data3</Key3>
</MyData>

Easy, isn't it? To load the same XML data back, you could use the following method:

internal static Dictionary LoadDictionary(string filename)
{
  // get the file's data
  Dictionary results = new Dictionary();
  XElement xml = XElement.Load(filename);

  // process the data
  foreach (XElement element in xml.Elements())
  {
    string key = element.Name.LocalName;
    string value = element.Value;
    results.Add(key, value);
  }

  // we are done
  return results;
}

Hope this helps!