【问题标题】:get the number of elements in an XML document获取 XML 文档中元素的数量
【发布时间】:2018-11-29 14:49:36
【问题描述】:

我需要在 java ( java dom ...) 中获取 xml 文件中的节点总数 在下面的文件中,元素的总数是 15

    <?xml version="1.0" encoding="UTF-8"?>
<personnes>
   <etudiant classe="P2">
      <nom>CynO</nom>
      <prenoms>
         <prenom>Nicolas</prenom>
         <prenom>Laurent</prenom>
      </prenoms>
      <age>25</age>
   </etudiant>
   <etudiant classe="P1">
      <nom>Superwoman</nom>
      <prenoms>
        <prenom>Sia</prenom>
        </prenoms>
        <age>34</age>
   </etudiant>
   <etudiant classe="P3">
      <nom>Don Corleone</nom>
      <age>28</age>
   </etudiant>
</personnes>

谢谢你

【问题讨论】:

  • 我相信你的标题应该是“获取 XML 文档中元素的数量”。节点是元素、属性、文本(包括元素之间的空格)、cmets 和文档本身。
  • 感谢您的评论。我改了

标签: java xml dom


【解决方案1】:

尝试使用以下代码 sn-p。它对我有用。

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class CountNoOfElements{

    public static void main(String args[]) throws Exception {
        String filepath = "test.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        NodeList nodeList = doc.getElementsByTagName("*");
        int count = nodeList.getLength();
        System.out.println("Total of elements : " + count);
    }   
}

【讨论】:

  • 不需要循环。 getElementsByTagName 只返回元素;这就是方法名称以“getElements”开头的原因。 int count = nodeList.getLength(); 就足够了。
  • @VGR,当然可以。更新了我的答案。感谢您指出。
  • 哦,谢谢你回答我。是的,这两种方法都适用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
相关资源
最近更新 更多