How to process XML File in java

I had an requirement to parse an incoming SOAP Message object and do certain manipulations over it. I had to do it outside the web service route, so there was no SOAP related process methods available for me. All I had was a xml file in the Input Stream.

I searched a lots of link for xml processing, used many libraries most of which I do not even remember the  name. Then my colleague and another contributor to these blogs suggested to use the DOM Parser provided by default in java. Though it was little confusing in the beginning, with the help of couple of other blogs, we managed to complete it without any external libraries. I have attached the code and the xml file content for your reference.

XML File
Name : test.xml

<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="">
        <ns2:RegisterComplaint xmlns:ns2="http://webservice/">
<Name> Shankar </Name>
<Age> 25 </Age>
<Job> Senior Technical Consultant </Job>
<Name> Pandi </Name>
<Age> 25 </Age>
<Job> Senior Technical Consultant </Job>
<Name> Santhosh </Name>
<Age> 25 </Age>
<Job> Senior Technical Consultant </Job>
Java Code:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 * @author shaan
public class Main {
    private static Document dom;
     * @param args the command line arguments
    public static void main(String[] args) {
        // TODO code application logic here
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           String file="/home/shaan/test.xml";
           dom = db.parse(file);
           Element docEle = dom.getDocumentElement();
                NodeList nl = docEle.getElementsByTagName("Name");
                int len = nl.getLength();
                String textVal = null;
if(nl != null && nl.getLength() > 0) {
                    for(int i=0;i<len;i++) {
                        Element el = (Element)nl.item(i);
textVal = el.getFirstChild().getNodeValue();
                        System.out.println("Name "+textVal);
        catch(Exception e){
            System.out.println("Exception "+e.toString());
Name  Shankar
Name  Pandi
BUILD SUCCESSFUL (total time: 0 seconds)

You can make use of this basic model and do various kinds of processing of the xml document.  Do leave your comments if at all you face anything.

Happy Working ... <3 <3 <3


  1. Use SAX parsing which is better than DOM( SAX is like a event based programming(triggers event when it finds a node) while DOM loads the entire XML document into the memory and when the XML document is very large java will run out of its heap space.


Post a Comment

Popular posts from this blog

Changing Timezone in Postgresql, Ubuntu

Display Logic and read only logic In Openbravo

My 10 years in Application Development