Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the leaves of an XML string with C#

Tags:

c#

.net

xml

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#?

like image 857
M. X Avatar asked Dec 07 '22 13:12

M. X


1 Answers

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);
like image 103
L.B Avatar answered Dec 19 '22 13:12

L.B