Count XML records by element name in Java

Create a document in memory and append two child elements. Query the finished document to count only elements with the requested tag name.

A simple example

Count elements named item

  1. Start with One child element named item
  2. Do this Count elements named item
  3. Result 1
Matching by name selects only the elements with that name.

Apply it to a real problem

  1. Start with An orders document with two order children
  2. Do this Count order elements
  3. Result 2
Counting the matching children gives the report its record total.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import javax.xml.parsers.DocumentBuilderFactory;

public class Main {
    public static void main(String[] args) throws Exception {
        var doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        var root = doc.createElement("orders");
        doc.appendChild(root);
        root.appendChild(doc.createElement("order"));
        root.appendChild(doc.createElement("order"));
        System.out.println(doc.getElementsByTagName("order").getLength());
        System.out.println(doc.getElementsByTagName("refund").getLength());
    }
}
Output
2
0

Official Java documentation