Parsing / Reading XML file in Java.

While working on a small requirement, I had to write a small piece of code that can parse an XML file in Java. Although there are number of libraries available in Java which does this task efficiently, I ended up in using normal Java XML parsing using org.w3c.dom parser.

You may want to copy this code and customize it to your to fit it for your need.

Following is the sample XML file that I used.

XML File

 

Source Code of XML Parser

Following is the source code of sample XML parser in Java that I used to parse sample 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 studentList = docEle.getElementsByTagName("student");

    // Print total student elements in document
    System.out
      .println("Total students: " + studentList.getLength());

    if (studentList != null && studentList.getLength() > 0) {
     for (int i = 0; i 

Following is the output of our XML parser.

Program Output

Root element of the document: students
Total students: 3
==============================
Name: John
Grade: B
Age: 12
==============================
Name: Mary
Grade: A
Age: 11
==============================
Name: Simon
Grade: A
Age: 18

You can customise this code for your input XML file.

View Comments

  • There is bug or bad display at line 33.
    if (studentList != null && studentList.getLength() > 0) {

  • i have made one project in eclipse for reading xml file, i have write one function for that

    function readXMLFile(){
    alert("calling");

    alert("DocumentBuildFactory instance");

    alert("Reading xml file");

    alert("normalize");

    alert(nodeName);
    }

    until the normalize it was working fine but when its try to fetch node name it will shows nothing

    could anybody help me to solve it?
    and one more thing where should i put xml file to read it from java file

  • [code language="java"]
    //To simplify further

    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;

    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;

    public class XMLReader{

    public static void main (String argv []){

    String[] TagNames = {"first","last","age"}; // Enter the node name as elements in an array
    try {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("C:\\JavaTesting\\file.xml"));// path of the xml file

    NodeList list = doc.getElementsByTagName("*");
    System.out.println("XML Elements: ");
    for (int i=0; i<list.getLength(); i++) {
    // Get element
    Element element = (Element)list.item(i);
    System.out.println(element.getNodeName());
    }

    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " +doc.getDocumentElement().getNodeName());

    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);

    for(int s=0; s<listOfPersons.getLength() ; s++){

    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){

    Element firstPersonElement = (Element)firstPersonNode;

    for (int i = 0; i < TagNames.length; i++) {

    NodeList firstNameList = firstPersonElement.getElementsByTagName(TagNames[i]);
    Element firstNameElement = (Element)firstNameList.item(0);

    NodeList textFNList = firstNameElement.getChildNodes();
    System.out.println(TagNames[i]+" : " + ((Node)textFNList.item(0)).getNodeValue().trim());

    }

    }//end of if clause

    }//end of for loop with s var

    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line "
    + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());

    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();

    }catch (Throwable t) {
    t.printStackTrace ();
    }
    //System.exit (0);

    }//end of main

    }
    // Still we can have a generic xml reader with dynamic tag names pick. :)
    [/code]

  • How do you parse this xml file.

    Ishan

    cards
    notes
    dice

    50 50 10
    offices

    Connor

    notes
    dice
    cards

    10 10 10
    security room

Share
Published by
Hanumant Shikhare
Tags: How-To Java reading xml sax parser xml xml parsing in java xml-parsing

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago