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.

Example

  1. student.xml
  2. DomParser.java

student.xml

<?xml version="1.0" encoding="UTF-8"?>
<student>
 <roll>101</roll>
 <name>Vikash</name>
 <address>Hyderabad</address>
</student>

 DomParser.java

package com.javagf.resource;

import java.io.IOException;

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);
 }
 }
 }

}

Output

roll : 101
name : Vikash
address : Hyderabad






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