Counting elements in an XML document

I am wondering if it is possible to count the number of elements in an XML document, it is desirable that it can use something similar to where (string)query.Attribute("attName") == att .

Using all my knowledge, I tried the following, but, unfortunately, I cannot get it to 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) { Count++; } } 

Thanks!

+6
c # xml windows-phone-7 silverlight
source share
3 answers

Given that doc is an instance of XDocument

 doc.Root.Descendants().Count(d => (string)d.Attribute("attName") == "value"); 
+10
source share

This is likely to be a good application to use XPath.

http://support.microsoft.com/kb/308333/en-us

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

0
source share
 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; 
0
source share

All Articles