DOM parser to count xml file elements in java

Steps to modify XML file:

1. Create a Document with DocumentBuilder class.
2. Parse XML file.
3. Get element list.
4. Print no. of elements.

Example:

DOMParserCountTest.java

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
/**
 * This class is used to count XML elements using DOM parser.
 * @author w3schools
 */
public class DOMParserCountTest {
	public static void main(String args[]) {
	  try {
		//File Path
		String filePath = "D:\\class.xml";
 
		//Read XML file.
		File inputFile = new File(filePath);
 
		//Create DocumentBuilderFactory object.
		DocumentBuilderFactory dbFactory =
                                DocumentBuilderFactory.newInstance();
 
		//Get DocumentBuilder object.
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
 
		//Parse XML file.
		Document document = dBuilder.parse(inputFile);
 
		//Get element by tag name.
		Node students = 
                     document.getElementsByTagName("students").item(0);
 
		//Get student element list.
		NodeList list = students.getChildNodes();
 
		//Print number of elements.
		System.out.println("Elements count: " + list.getLength());
 
	  } catch (Exception e) {
		e.printStackTrace();
	  }
	}
}

Output:

Elements count: 2

Download this example.
 
Next Topic: SAX XML parser in java with example.
Previous Topic: DOM XML parser to modify xml file in java.