Easy way to convert a Dictionary to xml and vice versa

前端 未结 6 1617
北海茫月
北海茫月 2020-11-30 22:13

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

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 23:00

    Dictionary to Element:

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

    Element to Dictionary:

    XElement rootElement = XElement.Parse("value");
    Dictionary dict = new Dictionary();
    foreach(var el in rootElement.Elements())
    {
       dict.Add(el.Name.LocalName, el.Value);
    }
    

提交回复
热议问题