Reputation: 1347
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
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 conditionnot(*)
Means that the current element has no child elementsUpvotes: 4
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