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#?
Count the XML elements (XPath)newXPath(); NodeList nodes = (NodeList) xpath. evaluate("//staff", doc, XPathConstants. NODESET); int count = nodes. getLength();
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 .
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.
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();
XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(XmlPath); var totalItems = xmldoc.SelectNodes( "/root/node/LastName/").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