This example focuses on how to count XML elements in Java.
Source Code
(1)Test.xml
Alice
phone:123456789
Bob
phone:987654321
(2)CountXMLElement.java
package com.beginner.examples;
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[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse("Test.xml");
NodeList list = doc.getElementsByTagName("context-param");
System.out.println("Elements of number is " + list.getLength());
}
}
Output:
Elements of number is 2
References
Imported packages in Java documentation: