Showing posts with label Parsing XML file in Java. Show all posts
Showing posts with label Parsing XML file in Java. Show all posts

Parsing / Reading XML file in Java Using org.w3c.dom parser

I have a Piece of code which can be used to Parse a XML file using java DOM Parser.

Step 1: Create a XML file as below

<?xml version="1.0"?>
<Employees>
    <Employee>
        <name>Melvyn</name>
        <grade>B</grade>
        <age>23</age>
    </Employee>
    <Employee>
        <name>Nixon</name>
        <grade>A</grade>
        <age>25</age>
    </Employee>
    <Employee>
        <name>Bruce</name>
        <grade>A</grade>
        <age>28</age>
    </Employee>
</Employees>

2.Java Code to Read the XML file

package net.viralpatel.java.xmlparser;
 
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 XMLParser {
 
    public void getAllUserNames(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            File file = new File(fileName);
            if (file.exists()) {
                Document doc = db.parse(file);
                Element docEle = doc.getDocumentElement();
 
                // Print root element of the document
                System.out.println("Root element of the document: "
                        + docEle.getNodeName());
 
                NodeList EmployeeList = docEle.getElementsByTagName("Employee");
 
                // Print total Employee elements in document
                System.out
                        .println("Total Employees: " + EmployeeList.getLength());
 
                if (EmployeeList != null && EmployeeList.getLength() > 0) {
                    for (int i = 0; i < EmployeeList.getLength(); i++) {
 
                        Node node = EmployeeList.item(i);
 
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
 
                            System.out
                                    .println("=====================");
 
                            Element e = (Element) node;
                            NodeList nodeList = e.getElementsByTagName("name");
                            System.out.println("Name: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
 
                            nodeList = e.getElementsByTagName("grade");
                            System.out.println("Grade: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
 
                            nodeList = e.getElementsByTagName("age");
                            System.out.println("Age: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
                        }
                    }
                } else {
                    System.exit(1);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    public static void main(String[] args) {
 
        XMLParser parser = new XMLParser();
        parser.getAllUserNames("c:\\test.xml");
    }
}

Following is the output of our XML parser.
Program Output

Root element of the document: students
Total Employees: 3
==============================
Name: Melvyn
Grade: B
Age: 23
==============================
Name: Nixon
Grade: A
Age: 25
==============================
Name: Bruce
Grade: A
Age: 28

How to read XML file in Java using DOM Parser

Here’s an example to demonstrate how to read a XML file in Java with DOM parser. The DOM interface is the easiest to understand. It parses an entire XML document and load it into memory, modeling it with Object for the traversal.

Step 1:Create a XML File

<?xml version="1.0"?>
<company>
    <Employee>
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
    </Employee>
    <Employee>
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>200000</salary>
    </Employee>
</company>

2.Create a Java File to Process this XML file

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

 public static void main(String argv[]) {

 try {

    File fXmlFile = new File("c:\\file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("Employee");
    System.out.println("-----------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

       Node nNode = nList.item(temp);      
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;

          System.out.println("First Name : "  + getTagValue("firstname",eElement));
          System.out.println("Last Name : "  + getTagValue("lastname",eElement));
          System.out.println("Nick Name : "  + getTagValue("nickname",eElement));
          System.out.println("Salary : "  + getTagValue("salary",eElement));

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

 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();   
 }

}