Java DOM Parser to Parse XML Document


Java DOM Parser To Parse XML Document

Java DOM Parser to Parse XML Document is important concept for every java developer because it’s quite typical to understand.

XML file

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

Java Code to parse XML

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.Node;
import org.w3c.dom.NodeList;

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

 public static void printAllContent(Node node) {
   switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
      printAllContent(node.getFirstChild());
      break;
   case Node.ELEMENT_NODE:
      System.out.print(node.getNodeName() + " : ");
     NodeList list = node.getChildNodes();
     for (int i = 0; i <= list.getLength(); i++) {
       if (list.item(i) != null) {
         printAllContent(list.item(i));
       }
    }
     break;
   case Node.TEXT_NODE:
     System.out.print(node.getNodeValue());
     break;
   }
 }

 public static void main(String[] args) {

 try {

   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document document = builder.parse(new File(FILE_PATH));
   printAllContent(document);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }

}

Output

 student-info : 
 roll : 101
 name : Vikas






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