简单的方法来转换字典&LT;字符串,字符串&GT; XML和反之亦然 [英] Easy way to convert a Dictionary<string, string> to xml and visa versa
本文介绍了简单的方法来转换字典&LT;字符串,字符串&GT; XML和反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
知道是否有一个快速的方法,可能与LINQ ?,到词典转换成XML文档。和方式向XML转换回字典。
XML可以关注一下:
&LT;根和GT;
&LT;密钥GT; VALUE&LT; /键&GT;
&LT;&KEY2 GT; VALUE&LT; /为key2&GT;
&LT; /根&GT;
解决方案
字典元素:
词典&LT;字符串,字符串&GT;字典=新词典&LT;字符串,字符串&GT;();
EL的XElement =新的XElement(根,
dict.Select(KV =&gt;新建的XElement(kv.Key,kv.Value)));
元素来解释:
的XElement rootElement的= XElement.Parse(&LT;根&GT;&LT;键&GT;价值&LT; /键&GT;&LT; /根&GT;);
字典&LT;字符串,字符串&GT;字典=新词典&LT;字符串,字符串&GT;();
的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屋!
查看全文