2015-04-08 61 views
0

我有一個XML格式如下的XML。這個XML被分配給一個XDocument對象。C# - 獲取XML元素的節點值和相應的計數

<root> 
<event> 
<command>A1</command> 
</event> 
<event> 
<command>B1</command> 
</event> 
<event> 
<command>A1</command> 
</event> 
<event> 
<command>C1</command> 
</event> 
</root> 

我需要獲取所有<command>節點的節點值和他們每個人出現的次數。在上述情況下,我需要的輸出將

A1 2 
B1 1 
C1 1 

我還需要上述結果進入對象,如下

var cmdList=from appinfo in doc.Root.Elements() 
        select new 
        { 
        Cname= ... 
        CCount =... 
        } 
+0

你嘗試過什麼? – bit

回答

3

使用GroupBy: -

var result = xdoc.Descendants("event") 
       .Where(x => !String.IsNullOrEmpty((string)x.Element("command"))) 
       .GroupBy(x => (string)x.Element("command")) 
       .Select(x => new 
          { 
           Value = x.Key, 
           Count = x.Count() 
          }); 
+0

是的,這正是我想要的!只有輕微的改善。我如何擺脫空值。其中一個x.Key值爲空。我的Where子句應該在哪裏 – mhn

+0

@mhn - 只需在分組之前過濾它,檢查我的更新。 –

+1

工作!非常感謝 – mhn