2014-04-08 79 views
2

我有一個XML文檔是這樣的:ASP.NET轉換XML字符串字典

<Tags> 
    <Key> 
    <Name>Model</Name> 
    <Value>Raggae</Value> 
    </Key> 
    <Key> 
    <Name>Rate</Name> 
    <Value>21</Value> 
    </Key> 
</Tags> 

我想從它創建一個字典,包含關鍵的名稱元素和價值元素的值。

請幫我。

這是我寫的代碼,我婉知道它是否足夠有效的:

IDictionary<string, string> XmlToDictionary(string data) 
{ 
    XElement rootElement = XElement.Parse(data); 
    var dict = new Dictionary<string, string>(); 
    foreach (var el in rootElement.Elements()) 
    { 
     if (el.Name.LocalName == "Key") 
     { 
      foreach (var sub in el.Elements()) 
      { 
       string key = null; 
       string val = null; 
       if (sub.Name.LocalName == "Name") key = sub.Value; 
       if (sub.Name.LocalName == "Value") val = sub.Value; 
       if (key != null && !dict.ContainsKey(key)) dict.Add(key, val); 
      } 
     }     
    } 
    return dict; 
} 
+0

http://whathaveyoutried.com?請告訴我們你到目前爲止的情況。 SO不是代碼編寫服務,如果您提供了自己的工作證據,您將得到更好的迴應。請參閱[幫助頁面](http://stackoverflow.com/help)。 – freefaller

+0

對不起,省略代碼 – Arsene

回答

2

我敢肯定,有可能是一個更優雅的解決方案,但是這會做到這一點:

功能

IDictionary<string, string> XmlToDictionary(string data) 
{ 
     XElement rootElement = XElement.Parse(data); 
     var names = rootElement.Elements("Key").Elements("Name").Select(n => n.Value); 
     var values = rootElement.Elements("Key").Elements("Value").Select(v => v.Value); 
     var list = names.Zip(values, (k, v) => new { k, v }).ToDictionary(item => item.k, item => item.v); 
     return list;  
} 

測試

var xmlString = @"<Tags> 
    <Key> 
    <Name>Model</Name> 
    <Value>Raggae</Value> 
    </Key> 
    <Key> 
    <Name>Rate</Name> 
    <Value>21</Value> 
    </Key> 
</Tags>"; 

Console.WriteLine(XmlToDictionary(xmlString)); 
+0

Thanx hutchonoid。有用。 – Arsene