0

I have an XML in below format. This XML is assigned to an XDocument object.

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

I need to fetch the Node Value for all <command> nodes and the number of times each of them occur. In the above case, my desired output would be

A1 2
B1 1
C1 1

I also need the above results to go into object as below

var cmdList=from appinfo in doc.Root.Elements()
                    select new
                    {
                     Cname= ...
                     CCount =...
                     }
1
  • Have you tried anything? Commented Apr 8, 2015 at 10:53

1 Answer 1

3

Use 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()
                             });
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this is just what I wanted! only slight improvement. How can i get rid of nulls. One of the x.Key value is null. Where should my where clause go
@mhn - Just filter it before grouping, check my update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.