Parsing / Reading XML file in Java.

java-xml-dukeWhile 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

<?xml version="1.0"?>
<students>
	<student>
		<name>John</name>
		<grade>B</grade>
		<age>12</age>
	</student>
	<student>
		<name>Mary</name>
		<grade>A</grade>
		<age>11</age>
	</student>
	<student>
		<name>Simon</name>
		<grade>A</grade>
		<age>18</age>
	</student>
</students>

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 < studentList.getLength(); i++) {

						Node node = studentList.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 students: 3
==============================
Name: John
Grade: B
Age: 12
==============================
Name: Mary
Grade: A
Age: 11
==============================
Name: Simon
Grade: A
Age: 18

You can customize this code for your input XML file.



6 Comments

  • JLemire wrote on 17 April, 2009, 20:44

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

  • Viral Patel wrote on 17 April, 2009, 21:48

    Thanks JLemire, I have updated the source and removed the typo error.

  • Ajay wrote on 2 August, 2009, 11:19

    Hi How to read this XML file and store it into HashSet?

  • anon wrote on 29 November, 2009, 5:46

    You want want to look at vtd-xml, the latest and most advanced parsing/indexing/XPath engine that offers a lot of cool features

    vtd-xml

  • Rajendra Jogas wrote on 18 December, 2010, 4:47

    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

  • Sander Wegdam wrote on 4 January, 2012, 20:23

    This is what i meaned by concepting Xml parsing in Java, great stuff!

Leave a Reply

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

*

Copyright © 2012 ViralPatel.net. All rights reserved.