Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific element Count in XML or XElement variable

Tags:

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

like image 863
Arian Avatar asked Jan 06 '12 21:01

Arian


People also ask

How do I count elements in XML?

Count the XML elements (XPath)newXPath(); NodeList nodes = (NodeList) xpath. evaluate("//staff", doc, XPathConstants. NODESET); int count = nodes. getLength();

What is @XMLElement?

XMLElement takes an element name for identifier , an optional collection of attributes for the element, and arguments that make up the content of the element. It returns an instance of type XMLType .

What is XElement in asp net?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

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(); 
like image 144
Ahmad Mageed Avatar answered Jan 04 '23 05:01

Ahmad Mageed


XmlDocument xmldoc = new XmlDocument();  xmldoc.Load(XmlPath); var totalItems = xmldoc.SelectNodes(          "/root/node/LastName/").Count; 
like image 29
Kasinatha Durai Avudaiyappan Avatar answered Jan 04 '23 06:01

Kasinatha Durai Avudaiyappan