How-To: Read an XML file using DOM parser in JAVA?

I was away on a vacation and therefore couldn’t write all these days. In this post, i will talk about reading an XML file using DOM parser in JAVA.

DOM parsing of XML

Below i am putting the XML file extract with it’s name.

XML file: ReadThisXML.xml

<?xml version=”1.0″?>

<organization>

<employee>

<firstname>Jack</firstname>

<lastname>Rose</lastname>

</employee>

<employee>

<firstname>Paul</firstname>

<lastname>McNealy</lastname>

</employee>

<employee>

<firstname>Vaibhav</firstname>

<lastname>Pandey</lastname>

</employee>

</organization>

The code below can be used to read this file and parse it using DOM parser.

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 XMLReader {

public static void main(String argv[]) {

try {
File file = new File(“c:\\ReadThisXML.xml”);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println(“Root element ” + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName(“employee”);
System.out.println(“Information of all employees”);

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

Node fstNode = nodeLst.item(s);

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

Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(“firstname”);
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println(“First Name : ” + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName(“lastname”);
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println(“Last Name : ” + ((Node) lstNm.item(0)).getNodeValue());
}

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

Advertisements

3 Responses

  1. Nice method…
    though i use magpie rss and php to parse xml in html..

    +1 for nice post

  2. Thanks . it will help me.

  3. how can i understand this code i am a new java developer.also running this code iam getting the exception.

    Content is not allowed in prolog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: