Read XML Node text value with Java DOM

Read XML Node text value with Java DOM

Read XML Node text value with Java DOM is an important aspect for every java developer ,Here we will read element and value of  XML file using DOM API in very simple way.


  1. student.xml


<?xml version="1.0" encoding="UTF-8"?>

package com.javagf.resource;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMParser {
 public static final String FILE_NAME = "D:\\REST\\AllMethod\\XML\\student.xml";

 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document document = builder.parse(FILE_NAME);

   //Go to the Roll element
   NodeList nodeList = document.getFirstChild().getChildNodes();
   //Read element one by one
   for (int i = 0; i < nodeList.getLength(); i++) {
     Node node = nodeList.item(i);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
        //get xml element name
       String name = node.getNodeName();
      //get xml element value
     String value = node.getTextContent();
     System.out.println(name +" : "+value);



roll : 101
name : Vikash
address : Hyderabad

Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: Sales: +91 8085506229