Easy way to convert a Dictionary<string, string> to xml and vice versa

Viewed 75030

Wondering if there is a fast way, maybe with linq?, to convert a Dictionary<string,string> into a XML document. And a way to convert the xml back to a dictionary.

XML can look like:

<root>
      <key>value</key>
      <key2>value</key2>
</root>
7 Answers

Dictionary to Xml is already answered by @LorenVS

However I found missing answer XML to Dictionary using Linq:

 // this could be XElement.Parse("<object attr='attr1'>value</object>") but lets do a file read, for more variety.
 var doc = new XmlDocument();
 doc.Load(fileName); 
 //also lets read attribiute and value as it hasnt been done above aswell.
 Dictionary<string, string> dict = 
 doc.DocumentElement.ChildNodes.OfType<XmlElement>()
    .ToDictionary(o => o.GetAttribute("attr"), o => o.Value)); 
Related