Count leaves of XML string using C #

Is there an easy way to get the number of all sheets of an XML string (XML document is provided as a string) using C #?

+4
source share
2 answers
XDocument xDoc = XDocument.Parse(xml); var count = xDoc.Descendants().Where(n => !n.Elements().Any()).Count(); 

or as suggested by @sixlettervariables

 var count = xDoc.Descendants().Count(e => !e.HasElements); 
+11
source

Here's how to do it with XPath (borrow from helio):

 XmlDocument doc = new XmlDocument(); doc.LoadXml("..."); int count = doc.SelectNodes("//*[not(*)]").Count; 
  • // Means to match all descendants
  • * Denotes any XML element
  • [] Indicates a condition
  • not(*) Means that the current element has no children
+4
source

All Articles