2014-02-26 17 views
0

我有一個這樣的文件:解析XML並將其添加爲鍵值對

<dict> 
<key> 1</key> 
<string>AAA</string> 
<key> 2</key> 
<string>BBB</string> 
<key> 3</key> 
<string>CCC</string> 
<key> 4</key> 
<string>DDD</string> 
</dict> 

我解析這樣的:

Dictionary<string, string> dict = doc.Root.Elements("dict") 
        .ToDictionary(c => (string)c.Element("key"), 
           c => (string)c.Element("string")); 

      foreach (KeyValuePair<string, string> item in dict) 
      { 
       Debug.WriteLine("Key and Valkue is ", item.Key, item.Value); 
      } 

但它不是打印的值,並且如果用戶傳遞密鑰作爲行1我需要獲得其相應的值?在Java中,我們使用hashMap來實現這一點,我新來的C#,如何實現這一目標?我在這裏做錯了什麼?

+0

的順序計數儘管你的XML似乎是有效的,這是不好的結構。你不能指望元素的順序,所以'Line 1,DDD'對也是有效的。 –

+0

@ L.B但是在JAVA中,我能夠完美地使用HashMap來完成它,但是我們如何在c#中實現這個目標?你能建議我嘗試一下嗎? – user2056563

+0

查看我的答案然後, –

回答

1
var xmlDict = XDocument.Load(filename).Root.Element("dict"); 
var dict = xmlDict.Elements("key") 
      .Zip(xmlDict.Elements("string"), (k, s) => new KeyValuePair<string, string>(k.Value, s.Value)) 
      .ToDictionary(x=>x.Key,x=>x.Value); 

PS:不要忘了,因爲我在評論中說,你不應該元素

+1

這就是我一直在尋找的感謝 – user2056563

+0

你可以請看看它在這裏http://stackoverflow.com/questions/22044034/overriding-methods-from-library-project – user2056563