Java XML Tutorial

How to count XML elements in Java

This article shows how to use DOM parser, SAX parser, and XPath to count the number of a specified XML element in Java.

Table of contents

P.S Tested with Java 11.

1. An XML file

The below is an XML file for testing, and later all the examples will count the number of XML elements known as "staff", and the output is 2.

src/main/resources/staff.xml

<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff id="1001">
        <name>mkyong</name>
        <role>support</role>
    </staff>
    <staff id="1002">
        <name>yflow</name>
        <role>admin</role>
    </staff>
</company>

2. Count the XML elements (DOM Parser)


  // DOM APIs
  NodeList list = doc.getElementsByTagName("staff");
  System.out.println(list.getLength());   // 2

Below is a complete DOM parser example to count the number of "staff" elements in an XML file.

CountElementXmlDomParser.java

package com.mkyong.xml.dom;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CountElementXmlDomParser {

  private static final String FILENAME = "src/main/resources/staff.xml";

  public static void main(String[] args) {

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      try (InputStream is = new FileInputStream(FILENAME)) {

          DocumentBuilder db = dbf.newDocumentBuilder();

          Document doc = db.parse(is);

          // get all elements known as "staff"
          NodeList list = doc.getElementsByTagName("staff");

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

      } catch (ParserConfigurationException | SAXException | IOException e) {
          e.printStackTrace();
      }

  }

}

Output

Terminal

  Number of staff elements : 2

3. Count the XML elements (XPath)


  XPath xpath = XPathFactory.newInstance().newXPath();
  NodeList nodes = (NodeList)
          xpath.evaluate("//staff", doc, XPathConstants.NODESET);
  int count = nodes.getLength();

Below is a complete DOM and XPath example to count the number of "staff" elements in an XML file.

CountElementXmlDomXPath.java

package com.mkyong.xml.dom;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CountElementXmlDomXPath {

  private static final String FILENAME = "src/main/resources/staff.xml";

  public static void main(String[] args) {

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      try (InputStream is = new FileInputStream(FILENAME)) {

          DocumentBuilder db = dbf.newDocumentBuilder();

          Document doc = db.parse(is);

          // get all elements known as "staff"
          // xpath
          XPath xpath = XPathFactory.newInstance().newXPath();
          NodeList nodes = (NodeList)
                  xpath.evaluate("//staff", doc, XPathConstants.NODESET);
          int count = nodes.getLength();

          System.out.println("Number of staff elements : " + count);

      } catch (ParserConfigurationException | SAXException |
                IOException | XPathExpressionException e) {
          e.printStackTrace();
      }

  }

}

Output

Terminal

  Number of staff elements : 2

4. Count the XML elements (SAX Parser)

Below is a complete SAX Parser example to count the number of "staff" elements in an XML file.

4.1 We can create a SAX handler and count the elements in the startElement() method.

CountElementHandlerSax.java

package com.mkyong.xml.sax.handler;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class CountElementHandlerSax extends DefaultHandler {

  private final String elementName;
  private Integer count = 0;

  public String getElementName() {
      return elementName;
  }

  public Integer getCount() {
      return count;
  }

  public CountElementHandlerSax(String elementName) {
      this.elementName = elementName;
  }

  @Override
  public void startElement(String uri, String localName,
          String qName, Attributes attributes)
          throws SAXException {
      if (qName.equalsIgnoreCase(getElementName())) {
          count++;
      }
  }

}

4.2 Run the SAX parser with the above CountElementHandlerSax.

ReadXmlSaxParser.java

package com.mkyong.xml.sax;

import com.mkyong.xml.sax.handler.CountElementHandlerSax;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;

public class ReadXmlSaxParser {

  private static final String FILENAME = "src/main/resources/staff.xml";

  public static void main(String[] args) {

      SAXParserFactory factory = SAXParserFactory.newInstance();

      try {

          SAXParser saxParser = factory.newSAXParser();

          // count elements name known as "staff"
          CountElementHandlerSax countStaffHandler =
                              new CountElementHandlerSax("staff");
          saxParser.parse(FILENAME, countStaffHandler);

          System.out.println("Number of staff elements : "
              + countStaffHandler.getCount());

      } catch (ParserConfigurationException | SAXException | IOException e) {
          e.printStackTrace();
      }

  }

}

Output

Terminal

  Number of staff elements : 2

5. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-xml

$ cd src/main/java/com/mkyong/xml/dom/

$ cd src/main/java/com/mkyong/xml/sax/

6. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Vignesh Govindhan
3 months ago

How can we count a xml element of each child nodes?

Aman
1 year ago

One of the best working code article.