views:

518

answers:

2

Wondering if there is a fast way, maybe with linq?, to convert a Dictionary 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>
+4  A: 

Dictionary to Element:

Dictionary<string, string> dict = new Dictionary<string,string>();
XElement el = new XElement("root",
    dict.Select(kv => new XElement(kv.Key, kv.Value)));

Element to Dictionary:

XElement rootElement = XElement.Parse("<root><key>value</key></root>");
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach(var el in rootElement.Elements())
{
   dict.Add(el.Name.LocalName, el.Value);
}
LorenVS
you can use ToDictionary... *rootElement.Elements().ToDictionary( key => key.Name, val => val.Value);*
Stan R.
+3  A: 

You can use DataContractSerializer. Code below.

    public static string SerializeDict()
    {
        IDictionary<string, string> dict = new Dictionary<string, string>();
        dict["key"] = "value1";
        dict["key2"] = "value2";
        // serialize the dictionary
        DataContractSerializer serializer = new DataContractSerializer(dict.GetType());

        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter writer = new XmlTextWriter(sw))
            {
                // add formatting so the XML is easy to read in the log
                writer.Formatting = Formatting.Indented;

                serializer.WriteObject(writer, dict);

                writer.Flush();

                return sw.ToString();
            }
        }
    }
dcp