Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count specific XML Nodes within XML

Tags:

c#

xml

asp.net

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?

like image 395
Jobi Avatar asked Nov 29 '22 18:11

Jobi


1 Answers

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();
like image 155
Darin Dimitrov Avatar answered Dec 16 '22 03:12

Darin Dimitrov