DOM XML parser to parse XML file in java

Steps to read a XML file:

1. Create a Document with DocumentBuilder class.
2. Fetch the root element.
3. Process the child elements.
4. Process the attributes.



<?xml version="1.0"?>
   <student rollno="1">
   <student rollno="2">
   <student rollno="3">

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 * This class is used to parse XML document using DOM parser.
 * @author w3spoint
public class DOMParserReadTest {
	public static void main(String args[]){
		try {
		//File Path
		String filePath = "D:\\StudentTest.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);
		//Print root element.
		System.out.println("Root element:" 
			  + document.getDocumentElement().getNodeName());
		//Get element list.
		NodeList nodeList = 
		//Process element list.
		for (int temp = 0; temp < nodeList.getLength(); temp++) {
	            Node nNode = nodeList.item(temp);
	            System.out.println("\nCurrent Element:" 
	               + nNode.getNodeName());
	            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
	               Element eElement = (Element) nNode;
	               System.out.println("Roll no: " 
	                  + eElement.getAttribute("rollno"));
	               System.out.println("First Name: " 
	                  + eElement.getElementsByTagName("firstname")
	               System.out.println("Last Name: " 
	               + eElement.getElementsByTagName("lastname")
	               System.out.println("Marks: " 
	               + eElement.getElementsByTagName("marks")
		} catch (Exception e) {


Root element:class
Current Element:student
Roll no: 1
First Name: Swati
Last Name: Aneja
Marks: 80
Current Element:student
Roll no: 2
First Name: Prabhjot
Last Name: Kaur
Marks: 70
Current Element:student
Roll no: 3
First Name: Nidhi
Last Name: Gupta
Marks: 75

Download this example.
Next Topic: DOM XML parser to create xml file in java.
Previous Topic: Java DOM XML parser.


Please Share