M. X
M. X

Reputation: 1347

Count the leaves of an XML string with C#

Is there a simple way to get the number of all leaves of an XML string (XML document is provided as a string) with C#?

Upvotes: 4

Views: 434

Answers (2)

Steven Doggart
Steven Doggart

Reputation: 43743

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

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

Upvotes: 4

L.B
L.B

Reputation: 116168

XDocument xDoc = XDocument.Parse(xml);
var count = xDoc.Descendants().Where(n => !n.Elements().Any()).Count();

or as @sixlettervariables suggested

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

Upvotes: 11

Related Questions