I'm fresher to c#. i've to parse the xml document and have to count the specific node of the childnodes.
eg:
<Root>
<Id/>
<EmployeeList>
<Employee>
<Id/>
<EmpName/>
</Employee>
<Employee>
<Id/>
<EmpName/>
</Employee>
<Employee>
<Id/>
<EmpName/>
</Employee>
</EmployeeList>
</Root>
In this xml, how do I count the "Employee" nodes??
How can i parse and get the solution using XmlDocument class in C#?
int Count = doc.SelectNodes("Employee").Count;
You can use XPath
var xdoc = XDocument.Load(path_to_xml);
var employeeCount = (double)xdoc.XPathEvaluate("count(//Employee)");
XmlDocument doc = new XmlDocument();
doc.LoadXml(XmlString);
XmlNodeList list = doc.SelectNodes("Root/EmployeeList/Employee");
int numEmployees = list.Count;
if the xml is from a file, use
doc.Load(PathToXmlFile);
Using linq to xml you can do:
XElement xElement = XElement.Parse(xml);
int count = xElement.Descendants("Employee").Count();
This assumes you have your xml in the string xml.
I would highly recommend using the System.Xml.Linq
library instead. it is much better than the one you are trying to use. Once you have loaded your XDocument, you can just get the root node and do something along the lines of:
//Parse the XML into an XDocument
int count = 0;
foreach(XElement e in RootNode.Element("EmployeeList").Elements("Employee"))
count++;
This code isn't exact, but you can look here for more complex examples: http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.