Skip navigation.
Home

Parsing XML file using DOM

By, Ahmed Hashim

In this article, I'll show you how to parse a XML file using JAXP API's.

You can parse an XML file using SAX (Simple API's for XML) or DOM (Document Object Model)

I'll not state the differences between SAX and DOM on the time but I want to show you how to quickly parse your XML file using DOM.

Prepare your XML file:

First I'll make a simple XML file contains books, every book element will contain the category, title and author. I am assuming that you are familiar with XML. 

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <book category="technical">
        <title>Getting started with web service</title>
        <author>Karen Sato</author>
    </book>
    <book category="Reference">
        <title>History of typewriter</title>
        <author>Luke Fassoso</author>
    </book>
    <book category="Cookery">
        <title>An Introduction to Egg-Plants</title>
        <author>Joo Woo</author>
    </book>
</catalog>

Setup DOM Parser:

You should first get instance from the Dom Parser using the following lines of code the parse the xml file. 

public static void main(String[] args)
    {
        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("books.xml");
            DomParser dom = new DomParser();
            dom.createNode(doc);
            dom.parseNode(doc);
        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (SAXException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
       
    }
Parse XML Nodes recursively :

This function is a recursive one, it will loop over the xml elements recursively to get all data in the xml file. 

public void parseNode(Node node)throws IOException
    {
        NodeList nodes = null;
        if(node.getNodeType() == Node.DOCUMENT_NODE)
        {
            System.out.println("/* Catalog contain books*/");
       
        nodes = node.getChildNodes();
        if(nodes != null)
        {
            for (int i = 0; i < nodes.getLength(); i++)
            {
                parseNode(nodes.item(i));
            }
        }
        }
        else if(node.getNodeType() == Node.ELEMENT_NODE)
        {
            NamedNodeMap attrs = node.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++)
            {
                System.out.println("Category: "+attrs.item(i).getNodeValue());
            }
            if(node.getNodeName().equals("title"))
            {
                System.out.print("Title:");
            }
            else if(node.getNodeName().equals("author"))
            {
                System.out.print("Author:");
            }
            nodes = node.getChildNodes();
            if(nodes != null)
            {
                for (int i = 0; i < nodes.getLength(); i++)
                {
                    parseNode(nodes.item(i));
                }
            }
        }
        else if(node.getNodeType() == Node.TEXT_NODE)
        {
            if(node.getNodeValue().length()>3)
            {
                System.out.println(node.getNodeValue());
            }
        }
       
    }

Add new Node: 

public void createNode(Document doc)throws IOException
    {
        Node rootNode = doc.getDocumentElement();
        Element element = doc.createElement("book");       
        element.setAttribute("category","Java");
       
        Node nodeTitle = doc.createElement("title");
        Text textTitle = doc.createTextNode("Java world");
        nodeTitle.appendChild(textTitle);
       
        Node nodeAuthor = doc.createElement("author");
        Text textAuthor = doc.createTextNode("Ahmed Hashim");
        nodeAuthor.appendChild(textAuthor);
       
        element.appendChild(nodeTitle);
        element.appendChild(nodeAuthor);
       
        rootNode.appendChild(element);
       
    }

I hope that this short memo can help you to parse XML file.

There are many ways to do the job, more easier or harder but I think this way will be easy for you to understand.

I'll try later to add more details to explain the code and concept behind.

AttachmentSize
DomParser.java2.62 KB
books.xml410 bytes

thank you hashim

thank you hashim,
excellent &simple way as expected from you

we wait the details and concept behind.

Thanks&Regards,
Essam