read xml file using dom parser in java


Read xml file using dom parser in java

read xml file using dom parser in java and  how to read xml file in java is one of common need of a Java Developer

How to read xml file in java

XML file

<?xml version="1.0" encoding="UTF-8"?>
<student-info>
   <roll>101</roll>
   <name>Vikas</name>
</student-info>

Java Code

package com.javagf.parser;

import java.io.File;

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;

public class DisplayNodeNames {
 private static final String FILE_PATH = "D:\\DOMPracticeForWebsite\\DOM\\XML\\student.xml";

 public static void main(String[] args) {

 try {

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 Document document = builder.parse(new File(FILE_PATH));

 NodeList nodeList = document.getChildNodes();

   for (int i = 0; i <= nodeList.getLength(); i++) {
      Node node = nodeList.item(i);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) node;
          System.out.println(eElement.getElementsByTagName("roll").item(0).getTextContent());
          System.out.println(eElement.getElementsByTagName("name").item(0).getTextContent());

     }
   }
  } catch (Exception e) {
      e.printStackTrace();
  }
 }

}

Output

101
Vikas






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