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

时间:2013-07-16 13:54:17

标签: c# xml

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

e.g:

<Root>
   <Id/>
   <EmployeeList>
      <Employee>
         <Id/>
         <EmpName/>
      </Employee>
      <Employee>
         <Id/>
         <EmpName/>
      </Employee>
      <Employee>
         <Id/>
         <EmpName/>
      </Employee>
    </EmployeeList>
</Root>

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

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

5 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

您可以使用XPath

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

答案 2 :(得分:2)

XmlDocument doc = new XmlDocument();
doc.LoadXml(XmlString);

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

如果xml来自文件,请使用

doc.Load(PathToXmlFile);

答案 3 :(得分:2)

使用linq to xml,您可以:

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

这假设您的xml在字符串xml中。

答案 4 :(得分:0)

我强烈建议您使用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