2012-05-15 139 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());