2011-01-26 96 views
4

我有一個配置文件,如:使用LINQ to XML解析成字典

<ConfigurationFile> 
    <Config name="some.configuration.setting" value="some.configuration.value"/> 
    <Config name="some.configuration.setting2" value="some.configuration.value2"/> 
    ... 
</ConfigurationFile> 

我想讀這XML並將其轉換爲一個字典。我嘗試編碼這個謊言,但它顯然是錯誤的,因爲它不編譯。

Dictionary<string, string> configDictionary = (from configDatum in xmlDocument.Descendants("Config") 
               select new 
               { 
                Name = configDatum.Attribute("name").Value, 
                Value = configDatum.Attribute("value").Value, 
               }).ToDictionary<string, string>(Something shoudl go here...?); 

如果有人能告訴我如何得到這個工作,這將是非常有益的。我當然可以閱讀它

回答

14

下面給出更詳細的解答 - 您可以使用ToDictionary完全一樣,你在你的問題中寫道。在缺少的部分,你需要指定「關鍵選擇器」和「數值選擇器」這兩個函數告訴ToDictionary方法你正在轉換的對象的哪一部分是一個關鍵,哪一個是一個值。你已經提取了這兩個匿名類型,所以你可以寫:

var configDictionary = 
(from configDatum in xmlDocument.Descendants("Config") 
    select new { 
    Name = configDatum.Attribute("name").Value, 
    Value = configDatum.Attribute("value").Value, 
    }).ToDictionary(o => o.Name, o => o.Value); 

請注意,我刪除了泛型類型參數說明。 C#編譯器自動計算出這個數字(我們使用的是overload with three generic arguments)。但是,您可以避免使用匿名類型 - 在上述版本中,只需創建它即可臨時存儲該值。最簡單的版本將會是:

var configDictionary = 
    xmlDocument.Descendants("Config").ToDictionary(
    datum => datum.Attribute("name").Value, 
    datum => datum.Attribute("value").Value); 
+0

非常感謝。 – PolandSpring 2011-01-26 18:18:01

0

您致電ToDictionary需要一個鍵和值選擇器。與你有開始,也可以是

var dictionary = yourQuery.ToDictionary(item => item.Name, item => item.Value); 
+0

對不起,這對我來說不是很清楚。這段代碼去哪裏? – PolandSpring 2011-01-26 04:20:38

0

不需要查詢,因爲您只是在進行投影。將投影移至ToDictionary()

var configDictionary = xmlDocument.Descendants("Config") 
            .ToDictionary(e => e.Attribute("name").Value, 
               e => e.Attribute("value").Value);