如何计算XML文档中特定节点的子节点?

我对c#更新鲜。 我要解析xml文档,并且必须计算子节点的特定节点。

例如:

                 

在这个xml中,我如何计算“Employee”节点?

如何在C#中使用XmlDocument类解析并获得解决方案?

 int Count = doc.SelectNodes("Employee").Count; 

您可以使用XPath

 var xdoc = XDocument.Load(path_to_xml); var employeeCount = (double)xdoc.XPathEvaluate("count(//Employee)"); 

使用linq to xml你可以:

 XElement xElement = XElement.Parse(xml); int count = xElement.Descendants("Employee").Count(); 

假设您在字符串xml中包含xml。

 XmlDocument doc = new XmlDocument(); doc.LoadXml(XmlString); XmlNodeList list = doc.SelectNodes("Root/EmployeeList/Employee"); int numEmployees = list.Count; 

如果xml来自文件,请使用

 doc.Load(PathToXmlFile); 

我强烈建议使用System.Xml.Linq库。 它比你想要使用的要好得多。 一旦加载了XDocument,就可以获得根节点并执行以下操作:

 //Parse the XML into an XDocument int count = 0; foreach(XElement e in RootNode.Element("EmployeeList").Elements("Employee")) count++; 

这段代码并不准确,但您可以在这里查看更复杂的示例: http : //broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html