2012-05-15 137 views
0

我有以下XML:LinqToXml:解析字典

<Places Count='50'> 
<Place ID='1' Row='1' Place='1' Type='1' Fragment='0'></Place> 
<Place ID='2' Row='1' Place='2' Type='1' Fragment='0'></Place> 
<Place ID='3' Row='1' Place='3' Type='2' Fragment='0'></Place> 
<Place ID='4' Row='1' Place='4' Type='2' Fragment='0'></Place> 
<Place ID='5' Row='1' Place='5' Type='2' Fragment='0'></Place> 
//other tags 
</Places> 

我想Dictionary<int, int>包含以下內容:

1,2 // 0 element in the Dictionary (type =1; count = 2) 
2,3; // 1 element in the Dictionary (type =2; count = 3) 

第一個參數是XML Type,第二個參數是此類型的計數。

謝謝。

+0

所以...你嘗試過什麼? –

+0

我無法理解如何將它修改爲Dictionary – user1260827

回答

6

的LINQ to XML使用LINQ結合到對象,使這個非常簡單:

var dictionary = doc.Descendants("Place") 
        .GroupBy(x => (int) x.Attribute("Type")) 
        .ToDictionary(g => g.Key, g => g.Count()); 

它的效率不高,因爲它可能是,但我會用這個實現堅持,直到我發現它成爲了一個問題。

請注意,在字典中談論「0元素」是誤導性的 - 字典沒有可靠的排序:您不應該假設如果您遍歷鍵/值對,您將以任何特定順序看到它們。

1

查詢語法

var dict = (from place in root.Descendants("Place") 
     group place by (int)place.Attribute("Type") into g 
     select g).ToDictionary(g=>g.Key, g=>g.Count());