Friday, 4 October 2013

Read XML file in Java

In this tutorial we learn how to read xml file in java.

Here is the program to read a xml file from java.

we also call it to DOM parser.

ReadXml.java file


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;

/**
 *
 * @author rajnikant panchal
 */
public class ReadXml {

    public static void main(String[] args) {


        try {

            File xmlfile = new File("/root/Documents/college.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document parsedoc = db.parse(xmlfile);

            NodeList nodeList = parsedoc.getElementsByTagName("student");

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

                Node node = nodeList.item(i);


                if (node.getNodeType() == Node.ELEMENT_NODE) {

                    Element emnt = (Element) node;

                    System.out.println("Student id : " + emnt.getAttribute("stuId"));
                    System.out.println("First Name : " + emnt.getElementsByTagName("firstname").item(0).getTextContent());
                    System.out.println("Date of Birth : " + emnt.getElementsByTagName("dob").item(0).getTextContent());

                }
            }


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



Regards,
Rajnikant Panchal

No comments:

Post a Comment