How to get specific element Count in XML or XElement variable

36,837

Solution 1

Prerequisite: in order to use .Count() you need to import the namespace System.Linq:

using System.Linq;

You can filter the descendant elements using the Descendants method with the name "ID", then count the results:

int count = xml.Descendants("ID").Count();

Be aware that Descendants looks through all levels. If you had an element other than Person that also had an ID child element, you would want to be more specific. In that case, to count ID child elements that belong to Person elements, you would use:

int count = xml.Elements("Person")
               .Elements("ID")
               .Count();

Solution 2

XmlDocument xmldoc = new XmlDocument();
 xmldoc.Load(XmlPath);
var totalItems = xmldoc.SelectNodes(
         "/root/node/LastName/").Count;
Share:
36,837
Arian
Author by

Arian

Please vote-up this thread: RDLC Report Viewer for Visual Studio 2022

Updated on July 09, 2022

Comments

  • Arian
    Arian almost 2 years

    Consider this XML:

    <Employees>
        <Person>
            <ID>1000</ID>
            <Name>Nima</Name>
            <LName>Agha</LName>
        </Person>
        <Person>
            <ID>1001</ID>
            <Name>Ligha</Name>
            <LName>Ligha</LName>
        </Person>
        <Person>
            <ID>1002</ID>
            <Name>Jigha</Name>
            <LName>Jigha</LName>
        </Person>
        <Person>
            <ID>1003</ID>
            <Name>Aba</Name>
            <LName>Aba</LName>
        </Person>
    </Employees>
    

    I declare a XElement variable and create the XML assigning it to that. How I can get count of ID elements in this XML variable in C#?

  • Arian
    Arian over 12 years
    If you don't use Elemets("Employees") it returns 0 :-?
  • Ahmad Mageed
    Ahmad Mageed over 12 years
    @Nima based on your sample input Employees is the root node, and if you're using an XElement there's no need for Elements("Employee") to be part of the query. If it isn't the root element, then you can either include it, or use xml.Descendants("Person").Elements("ID").Count() instead, thereby avoiding the need to walk the XML element by element.
  • Jon Heggland
    Jon Heggland about 5 years
    Is this answer still current? As far as I can tell, Descendants()and Elements() both return an IEnumerable, which doesn't seem to have a Count()method. Am I missing something obvious?