Using LINQ , you can count the number of node instances (regardless of hierarchical position),
int nodeCount; using (StreamReader reader = new StreamReader(xmlFilePath)) { XElement rootElement = XElement.Load(reader); nodeCount = rootElement.Descendants(nodeName).Count(); }
For example, in this xml nodeCount will be 4 ( nodeName is "b"),
<a> <b>1</b> <b>2</b> <b> <c>3</c> </b> <d> <b>4</b> </d> </a>
If you want to maintain a hierarchical structure, use this code
string nodeXPath = "./b"; using (StreamReader reader = new StreamReader(xmlFilePath)) { XElement rootElement = XElement.Load(reader); nodeCount = rootElement.XPathSelectElements(nodeXPath).Count(); }
The result for the same example will now give a result as 3.
source share