Java reading xml file using DOM parser



package com.c4learn;

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 ReadXMLFile {

    public static void main(String argv[]) {

    try {

    File inputXMLFile = new File("C://Pritesh/Java Practise/input.xml");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    Document inputDocument = dBuilder.parse(inputXMLFile);
    
    System.out.println("Root element : "
                + inputDocument.getDocumentElement().getNodeName());
    System.out.println("----------------------------------------");
    
    inputDocument.getDocumentElement().normalize();
    NodeList inputDocNodeList = inputDocument
                .getElementsByTagName("Book");

    for (int i = 0; i < inputDocNodeList.getLength(); i++) {

        Node nNode = inputDocNodeList.item(i);

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                System.out.println("Book Name  : "
                    + eElement.getElementsByTagName("bookname").item(0)
                            .getTextContent());

                System.out.println("Book Price : "
                    + eElement.getElementsByTagName("price").item(0)
                            .getTextContent());

                System.out.println("Book Pages : "
                    + eElement.getElementsByTagName("pages").item(0)
                            .getTextContent());

                System.out.println("");
        }
    }

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