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.

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 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 =
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

No comments: