2014-05-13 29 views
0

我嘗試計數,然後顯示xml文件中有多少個innerText是相同的。我發現這個代碼來計算存在多少個相等的節點,但沒有多少等於innerText如何統計xml文件中相同innerText的數量?

var doc = new XmlDocument(); 
doc.Load(path_to_xml); 
var result = from XmlNode n in doc.SelectNodes("//task/*") 
      group n by n.InnerText into g 
      select new { 
       Text = g.Key, 
       Count = g.Count() 
      }; 

例如,我有一個這樣的XML:

<rootNode> 
    <foo> 
     <first>stackoverflow</first> 
     <second>stackoverflow</second> 
     <third>superuser</third> 
    </foo> 
</rootNode> 

現在,我應該得到這一結果:

stackoverflow: Count 2 
superuser: Count 1 

有沒有辦法做到這一點?我使用XmlDocument解析XML。

有什麼建議嗎? :)

+0

看起來這是對的innerText>'n組由n.InnerText到g'? – Yahya

+0

那就是我首先想到的,但它只是計數我的節點 – Tyler

+0

你想要什麼呢? – Yahya

回答

3

可能是這樣嗎?

使用LINQ to XML:

var result = XDocument.Parse(xml) 
    .Descendants("foo") 
    .Elements() 
    .GroupBy(x => x.Value) 
    .ToDictionary(x => x.Key, y => y.Count()); 

使用XmlDocument的:

var doc = new XmlDocument(); 
doc.LoadXml(xml); 

var node = doc.SelectSingleNode("//foo"); 
var result2 = node.ChildNodes 
    .Cast<XmlNode>() 
    .GroupBy(x=>x.InnerText) 
    .ToDictionary(x => x.Key, y => y.Count()); 

要顯示在消息框試試這個:

foreach (var pair in result) 
{ 
    MessageBox.Show(string.Format("{0} found {1} number of times", pair.Key, pair.Value)); 
} 
+0

感謝您的回答。是否有'XmlDocument'的東西? :) – Tyler

+0

@Tyler看看更新的答案有幫助 –

+0

好的,謝謝。如果我想顯示它(例如一個MsgBox),怎麼做到這一點?我嘗試了'MessageBox.Show(result2.ToString())',但它然後它(邏輯)顯示我'System.Collections.Generic.Dictionary2 [System.String,System.Int32]' – Tyler

0

對於您粘貼它會像XML這個:

var result = from XmlNode n in doc.SelectNodes("/rootNode/foo/*") 
      group n by n.InnerText into g 
      select new { 
       Text = g.Key, 
       Count = g.Count() 
      }; 

確保您的XPath是正確的......

傾銷結果來安慰可能是這樣的:

result.ToList().ForEach(r => Console.WriteLine(r.Text + ": Count " + r.Count)); 
+0

如何顯示統計的innerText的數量?例如在一個'MessageBox'中? :) – Tyler

+0

result.ToList()。ForEach(r => Console.WriteLine(r.Text +「」+ r.Count)); – st4hoo

相關問題