Hello, I am an Engineering Manager at Facebook with 13+ years in Ad Technology, Natural Language Processing and Data mining. (Learn More)
by Pravin Paratey

XML DOM in Java

Of late, I have been working with Java. And one of the issues that I faced was XML parsing. With so many libraries available, I decided to stick to jaxp. What follows is sample code to Tree walk over the nodes:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class Tester {
    public static void main(String args[]) 
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            org.w3c.dom.Document doc = builder.parse(new File(args[0]));
            NodeList nodes1 = doc.getChildNodes();
            for(int i=0; i<nodes1.getLength(); i++) {
                TreeWalk(nodes1.item(i), 0);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void TreeWalk(Node n, int level) 
    {
        if(n.getNodeType() != Node.TEXT_NODE) {
            for(int i=0; i<level; i++)
                System.out.print("  ");
            System.out.print(n.getNodeName() + ":");
        }
        else {
            System.out.println(n.getNodeValue().trim());
        }
        NodeList list = n.getChildNodes();
        for(int i=0; i<list.getLength(); i++) {
            TreeWalk(list.item(i), level+1);
        }
    }
}