简体   繁体   English

如何计算一个xml文件中相同innerText的数量?

[英]How to count the number of same innerText in an xml file?

I try to count and then display how many innerText in an xml file are the same. 我尝试计数,然后显示xml文件中有多少innerText相同。 I found this code to count how many equal nodes exists but not how many equal innerText . 我发现这段代码可以计算存在多少个相等的节点,但不能计算多少个相等的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()
             };

For example, I have an xml like this: 例如,我有一个这样的xml:

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

Now I should get that result: 现在我应该得到那个结果:

stackoverflow: Count 2
superuser: Count 1

Is there a way to do that? 有没有办法做到这一点? I'm parsing the XML using XmlDocument . 我正在使用XmlDocument解析XML。

Any suggestions? 有什么建议么? :) :)

May be this? 可能是这个吗?

Using Linq to Xml: 使用Linq转Xml:

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

Using XmlDocument: 使用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());

To show in Messagebox try this: 要在Messagebox中显示,请尝试以下操作:

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

For the XML that you pasted it would be like this: 对于您粘贴的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()
             };

make sure that your XPath is correct... 确保您的XPath是正确的...

dumping result to console could be like this: 将结果转储到控制台可能是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM