外部键值对数据到字典c#



我有一个外部资源,将信息保存为key-value pair(例如文件,通常是xml),我想将此信息加载到应用程序中作为Dictionary<Key,Value>(泛型)。我正在寻找任何序列化-反序列化机制或任何其他没有任何开销的更好方法。

外部资源示例如下,

  Id         Value
  in         India
  us         United States
  fr         France

(say file, typically an xml)

假设XML为

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

转换为Dictionary的代码

XElement rootElement = XElement.Parse("<root><key>value</key></root>");
Dictionary<string, string> dictionary= new Dictionary<string, string>();
foreach(var el in rootElement.Elements())
{
   dictionary.Add(el.Name.LocalName, el.Value);
}

string string的字典应该可以解决这个问题。

// read from XML or some place    
var dictionary = new Dictionary<string, string>();
dictionary.Add("in", "India");
dictionary.Add("us", "United States");
dictionary.Add("fr", "France");

XML

<Loc>
 <Id>in</Id>
 <Value>India</Value>
</Loc>
c#

Dictionary<string,string> map = new Dictionary<string,string>();
XElement xe = XElement.Load("file.xml");
var q = from data in xe.Descendants("Loc")
        select data;
foreach (var data in q)
{
  map.Add(data.Element("Id").Value,data.Element("Value").Value);
}

最新更新