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
- Start with One child element named item
- Do this Count elements named item
- Result 1
Apply it to a real problem
- Start with An orders document with two order children
- Do this Count order elements
- Result 2
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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());
}
}
2 0