How to read an XML file using java

To read an XML file using Java, you can use the javax.xml.parsers.DocumentBuilder class and its parse method. Here is an example of how you might use this class to read an XML file and print its contents to the console:

Example code to read an XML file using Java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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[] args) {

    try {
      File inputFile = new File("input.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(inputFile);
      doc.getDocumentElement().normalize();
      System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
      NodeList nList = doc.getElementsByTagName("student");
      System.out.println("----------------------------");
      for (int temp = 0; temp < nList.getLength(); temp++) {
         Node nNode = nList.item(temp);
         System.out.println("\nCurrent Element :" + nNode.getNodeName());
         if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            System.out.println("Student roll no : " 
               + eElement.getAttribute("rollno"));
            System.out.println("First Name : " 
               + eElement
               .getElementsByTagName("firstname")
               .item(0)
               .getTextContent());
            System.out.println("Last Name : " 
               + eElement
               .getElementsByTagName("lastname")
               .item(0)
               .getTextContent());
            System.out.println("Nick Name : " 
               + eElement
               .getElementsByTagName("nickname")
               .item(0)
               .getTextContent());
            System.out.println("Marks : " 
               + eElement
               .getElementsByTagName("marks")
               .item(0)
               .getTextContent());
         }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

This code reads an XML file called “input.xml” and prints the contents to the console. The XML file should be in the same directory as the Java file. The output will be a list of student elements with their attributes and child elements.

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

These lines import various classes and interfaces that are used in the code. The DocumentBuilder class is used to parse an XML document and create a tree-like representation of its contents in memory. The DocumentBuilderFactory class is used to create a new DocumentBuilder instance. The Document interface represents an XML document, and the NodeListNode, and Element interfaces represent nodes in an XML document. The File class is used to represent a file on the file system.

    try {
      File inputFile = new File("input.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(inputFile);
      doc.getDocumentElement().normalize();

These lines create a new File object for the XML file, create a new DocumentBuilderFactory and a new DocumentBuilder, and use the DocumentBuilder to parse the XML file and create a Document object. The normalize method is called on the root element of the Document to ensure that all text nodes are properly merged and that the document is ready for processing.

      for (int temp = 0; temp < nList.getLength(); temp++) {
         Node nNode = nList.item(temp);
         System.out.println("\nCurrent Element :" + nNode.getNodeName());
         if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            System.out.println("Student roll no : " 
               + eElement.getAttribute("rollno"));
            System.out.println("First Name : " 
               + eElement
               .getElementsByTagName("firstname")
               .item(0)
               .getTextContent());
            System.out.println("Last Name : " 
               + eElement
               .getElementsByTagName("lastname")
               .item(0)
               .getTextContent());
           

These lines print the text on the console using a for loop. This is a complete code to read an xml file using java

You may also read

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.