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 di
I was looking for the same thing with a little difference(string, object) and I solved like this:
public static XElement ToXML(this Dictionary dic, string firstNode)
{
IList xElements = new List();
foreach (var item in dic)
xElements.Add(new XElement(item.Key, GetXElement(item.Value)));
XElement root = new XElement(firstNode, xElements.ToArray());
return root;
}
private static object GetXElement(object item)
{
if (item != null && item.GetType() == typeof(Dictionary))
{
IList xElements = new List();
foreach (var item2 in item as Dictionary)
xElements.Add(new XElement(item2.Key, GetXElement(item2.Value)));
return xElements.ToArray();
}
return item;
}
...for a dictionary(nested):
var key2 = new Dictionary
{
{"key3", "value"},
{"key4", "value"},
};
var key = new Dictionary
{
{"key", "value"}
{"key2", key1},
};
...passing "root" as firstNode i get:
value
value
value
Edited!