Take the 2-minute tour ×

I am wondering if it is possible to count the number of elements in an XML document preferably being able to fitler using something similar to where (string)query.Attribute("attName") == att.

Using the best of my knowledge i have tried the following but unfortunatly i can't seem to make it work.

                        var listElements = reader.Elements("shortlist");

                        foreach (var element in listElements)
                            XElement _xml;
                            location.Position = 0;
                            System.IO.StreamReader file = new System.IO.StreamReader(location);
                            _xml = XElement.Parse(file.ReadToEnd());
                            XAttribute attName = _xml.Attribute("attN");

                             if (attName.Value == att)


share|improve this question
What version of Silverlight are you targeting? –  Rohan West Nov 25 '10 at 20:09
It is for windows phone 7 so as far as I am aware it is mainly 3 with some features of 4 –  Jamie Nov 25 '10 at 21:02
add comment

3 Answers

up vote 7 down vote accepted

Given that doc is an instance of XDocument

doc.Root.Descendants().Count(d => (string)d.Attribute("attName") == "value");
share|improve this answer
Thanks for the quick responce. Do I simply put int Count = doc.Root... to so I can use the count? –  Jamie Nov 25 '10 at 20:58
Yes, that should do it. –  Matt Ellen Nov 25 '10 at 21:03
The Where lambda can be simplified to d => (string)d.Attribute("attName") == "value" and since the Count has an overload that takes a condition you can remove the Where altogether and move the lambda inside the Count. –  AnthonyWJones Nov 25 '10 at 22:33
@AnthonyWJones: I didn't know that, thanks. –  Matt Ellen Nov 25 '10 at 23:01
Thanks works perfectly :) –  Jamie Nov 25 '10 at 23:07
show 8 more comments

That would probably be a good application for using XPath.


An xpath could be "count(//*[@attName='attValue'])".

share|improve this answer
Windows Phone 7 does not support XPath since its based on Silverlight 3. –  AnthonyWJones Nov 25 '10 at 22:38
add comment
XmlDocument x = XmlDocument.Load("data.xml");   //pls excuse if i got the syntax wrong
XmlNodeList n = x.SelectNodes("//*[@attName='attValue']");
//Selects any element occuring anywhere in the document with Attribute attName='attValue'

int tadaa = n.Count;
share|improve this answer
XmlDocument not available in silverlight / Windows Phone 7 –  AnthonyWJones Nov 25 '10 at 22:36
I did try this but I don't think silverlight supports the XmlNodeList function –  Jamie Nov 25 '10 at 23:07
Oops, sorry for double commenting, yes the correct syntax would be XDocument rather than xmlDocument –  Jamie Nov 25 '10 at 23:08
add comment

Your Answer


