See this XML:
<CMP>
<OMP3>
<personmenu>
<submenuid>502</submenuid>
<submenuid>503</submenuid>
</personmenu>
<accountsmenu>
<submenuid>517</submenuid>
<submenuid>518</submenuid>
<submenuid>519</submenuid>
</accountsmenu>
<reportsmenu>
<submenuid>522</submenuid>
<submenuid>528</submenuid>
<submenuid>536</submenuid>
</reportsmenu>
</OMP3>
<AMP3>
<admissionmenu>
<submenuid>702</submenuid>
<submenuid>703</submenuid>
</admissionmenu>
</AMP3>
</CMP>
I want to get the total count of nodes from this xml dynamically (C#). How can I do it? Any sample code?
Here's an example of counting all submenuid
nodes in your xml document without loading it into memory:
var nodeCount = 0;
using (var reader = XmlReader.Create("test.xml"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "submenuid")
{
nodeCount++;
}
}
}
Console.WriteLine(nodeCount);
Or if you prefer LINQ to XML:
var count = XDocument
.Load("test.xml")
.XPathSelectElements("//submenuid")
.Count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With