How to Read XML Data in Java ? - Java Fiddle

Breaking

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Thursday, 16 July 2015

How to Read XML Data in Java ?

If you are a beginner to XML using Java then this is the perfect sample to parse a XML file create Java Objects and manipulate them.


Follwing is the staff.xml File whom data we will read via Java Program
<company>
    <staff id="101">
        <firstname>AMAN</firstname>
        <lastname>RAWAT</lastname>
        <nickname>AMI</nickname>
        <salary>20000</salary>
    </staff>
    <staff id="102">
        <firstname>ANIL</firstname>
        <lastname>BISHT</lastname>
        <nickname>ANI</nickname>
        <salary>19000</salary>
    </staff>
    <staff id="103">
        <firstname>GEETA</firstname>
        <lastname>KULBE</lastname>
        <nickname>GT</nickname>
        <salary>18500</salary>
    </staff>
</company>

Follwing is the XmlReader.java By which we will read xml file data

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 XmlReader {
 public static void main(String arg[]) {
  try {
   File fXmlFile = new File("./staff.xml");
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(fXmlFile);
   doc.getDocumentElement().normalize();
   System.out.println("Root Tag of XML Doc is : " + doc.getDocumentElement().getNodeName());
   NodeList nList = doc.getElementsByTagName("staff");
   System.out.println("----------------------------");
   for (int i = 0; i < nList.getLength(); i++) {
    Node nNode = nList.item(i);
    System.out.println("Current Element: " + nNode.getNodeName());
    if (nNode.hasChildNodes()) {
     Element el = (Element) nNode;
     System.out.println("Staff ID : " + el.getAttribute("id"));
     System.out.println("First Name : " + el.getElementsByTagName("firstname").item(0).getTextContent());
     System.out.println("Last Name : " + el.getElementsByTagName("lastname").item(0).getTextContent());
     System.out.println("Nick Name " + el.getElementsByTagName("nickname").item(0).getTextContent());
     System.out.println("Salary : " + el.getElementsByTagName("salary").item(0).getTextContent());
    }
   }
  } catch (Exception e) {
   System.out.println("Exception : " + e.getMessage());
  }
 }
}

Post Bottom Ad

Responsive Ads Here