【问题标题】:How to count the childnodes for the specific node in the XML document?如何计算 XML 文档中特定节点的子节点?
【发布时间】:2013-07-16 13:54:17
【问题描述】:

我对 c# 比较陌生。我必须解析 xml 文档并且必须计算子节点的特定节点。

例如:

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

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

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

【问题讨论】:

    标签: c# xml


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      int Count = doc.SelectNodes("Employee").Count;
      

      【讨论】:

      • 这是正确的吗? XmlElement docEle=doc.DocumentElement; XmlNodeList 节点=docEle.ChildNodes; for(int i=0;i
      【解决方案3】:

      你可以使用 XPath

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

      【讨论】:

      • 为什么要转换成 double 而不是 int?
      • @JohanLarsson 它会抛出InvalidCastException。此处的选项转换为 double 然后转换为 int (int)(double)xdoc.XPathEvaluate
      【解决方案4】:

      使用 linq to xml 你可以做到:

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

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

      【讨论】:

        【解决方案5】:
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(XmlString);
        
        XmlNodeList list = doc.SelectNodes("Root/EmployeeList/Employee");
        int numEmployees = list.Count;
        

        如果 xml 来自文件,则使用

        doc.Load(PathToXmlFile);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-31
          • 1970-01-01
          相关资源
          最近更新 更多