简单的方法来转换字典<字符串,字符串> XML和反之亦然 [英] Easy way to convert a Dictionary<string, string> to xml and visa versa

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

问题描述

知道是否有一个快速的方法,可能与LINQ ?,到词典转换成XML文档。和方式向XML转换回字典。

XML可以关注一下:

 <根和GT;
      <密钥GT; VALUE< /键>
      <&KEY2 GT; VALUE< /为key2>
< /根>


解决方案

字典元素:

 词典<字符串,字符串>字典=新词典<字符串,字符串>();
EL的XElement =新的XElement(根,
    dict.Select(KV =>新建的XElement(kv.Key,kv.Value)));

元素来解释:

 的XElement rootElement的= XElement.Parse(<根><键>价值< /键>< /根>);
字典<字符串,字符串>字典=新词典<字符串,字符串>();
的foreach(VAR EL在rootElement.Elements())
{
   dict.Add(el.Name.LocalName,el.Value);
}

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>

解决方案

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

这篇关于简单的方法来转换字典&LT;字符串,字符串&GT; XML和反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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