JavaでXML要素を数える方法 - (DOM Parser)

JavaでXML要素をカウントする方法-(DOMパーサー)

この例では、DOM Parserを使用してXMLファイル内の要素の総数をカウントする方法を示します。 最初に要素名を検索してから、NodeList.getLength()を使用して使用可能な要素の総数を取得できます。

    NodeList list = doc.getElementsByTagName("staff");
    System.out.println("Total of elements : " + list.getLength());

ファイル:file.xml


    
        yong
        mook kim
        example
        2000000
        29
    
    
        low
        yin fong
        fong fong
        1000000
    
    
        Ali
        Baba
        Alibaba
        199000
        40
    

File : CountXMLElement.java –使用可能な「staff」要素の総数を検索します。

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CountXMLElement {

  public static void main(String argv[]) {

    try {
        String filepath = "c:\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        NodeList list = doc.getElementsByTagName("staff");

        System.out.println("Total of elements : " + list.getLength());

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (SAXException sae) {
        sae.printStackTrace();
    }
  }
}

出力

Total of elements : 3