A Simple Way to Read an XML File in Java
by Kiran PaiWednesday, 3rd August 2005
This is the simplest way to read data from an XML file into a Java program. I have also included some basic error checking, so you can directly cut-paste this code with a few changes ofcourse. All you have to do is change the XML tags within the program to match those that are present in your XML file.
<?xml version="1.0"?>
<book>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
</book>
Total no of people : 3
First Name : Kiran
Last Name : Pai
Age : 22
First Name : Bill
Last Name : Gates
Age : 46
First Name : Steve
Last Name : Jobs
Age : 40
The Java program to read the above XML file is shown below. Go through the program twice and you will understand all its parts. It may look intimidating at first sight, but believe me its very simple.
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; </font>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">public class ReadAndPrintXMLFile{
</font>
<blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">public static void main (String argv []){
try {
</font>
<blockquote><blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));
// 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);</font>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">for(int s=0; s<listOfPersons.getLength() ; s++){</font>
<blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){</font>
<blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
Element firstPersonElement = (Element)firstPersonNode;
//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
//-------
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
//----
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
//------</font>
</blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
}//end of if clause</font>
</blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
}//end of for loop with s var</font>
</blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
}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);</font>
</blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">}//end of main</font>
</blockquote>
<font face="Verdana, Arial, Helvetica, sans-serif" size="-1">
}
There are better implementations of reading XML files which would work for any XML file. The above one would require a few changes every time the XML tag names change. But this is much more simpler than the other programs.
© Kiran Pai