DOM parser to count xml file elements in java

The DOM refers to Document Object Model. The DOM parses the XML file, creates the DOM objects and loads it into the memory in the tree structure. Use getLength() method of NodeList class to count total no. of elements in the XML file.

Note: DOM is simple and easy to use but it consume lots of memory and slow.

The XML refers to the EXtensible Markup Language which is used to store and transport the data. XML not provides any predefined tags. We have to define our own tags. Every opening XML tag must have a closing tag. XML tags are case sensitive and must be completely nested.

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.


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 javawithease
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 =
		//Get DocumentBuilder object.
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		//Parse XML file.
		Document document = dBuilder.parse(inputFile);
		//Get element by tag name.
		Node students = 
		//Get student element list.
		NodeList list = students.getChildNodes();
		//Print number of elements.
		System.out.println("Elements count: " + list.getLength());
	  } catch (Exception e) {


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.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.