Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count child nodes on XDocument

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

I looked for a count method or property and could not find one.

Thanks Leo

like image 911
MammothOne Avatar asked Aug 18 '11 14:08

MammothOne


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
like image 136
Thomas Levesque Avatar answered Oct 14 '22 19:10

Thomas Levesque


Alternatively ... if you know that the name of the elements are never going to 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();
like image 28
ablaze Avatar answered Oct 14 '22 19:10

ablaze