转换Dictionary< string,string>的简单方法到xml,反之亦然 [英] Easy way to convert a Dictionary<string, string> to xml and vice versa

查看:84
本文介绍了转换Dictionary< string,string>的简单方法到xml,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有一种快速的方法(也许使用linq?)将Dictionary<string,string>转换为XML文档.还有一种将xml转换回字典的方法.

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看起来像:

<root>
      <key>value</key>
      <key2>value</key2>
</root>

推荐答案

字典到元素:

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

字典元素:

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);
}

这篇关于转换Dictionary&lt; string,string&gt;的简单方法到xml,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆