Count child nodes on XDocument

Is there a way to count child nodes in an XDocument?

I was looking for a method or property count and could not find it.

Thanks Leo

+8
c # xml linq linq-to-xml
source share
2 answers
var doc = XDocument.Load(fileName); int descendantsCount = doc.Descendants().Count(); // counts ALL descendants elements int childrenCount = doc.Root.Elements().Count(); // counts direct children of the root element 
+14
source share

Alternatively ... if you know that the name of the elements will never change and they always exist,

 XDocument xD = XDocument.Load(XmlFullFileName); XElement xE_ParameterSets = xD.Root.Element("Report").Element("ParameterSets"); int index = ((IEnumerable<XElement>)xE_ParameterSets.Elements()).Count(); 
+2
source share

All Articles