Friday 19 February 2016

How to get all node names from XML in java

This code logic will help to get all the node names including child nodes from the XML file.

Parsing a below sample XML file:

<USER>
<NAME>Gopal Aggarwal</NAME>
<AGE>26</AGE>

<ADDRESS>
        <CITY> Bangalore</CITY>
        <STATE>Karnataka</STATE>
</ADDRESS>
</USER>

I am create a Set of unique node and print the output in the end.

package com.info.gopal.xml.parsing;

import java.io.File;
import java.io.IOException;

import java.util.LinkedHashSet;
import java.util.Set;

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

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

import org.xml.sax.SAXException;


public class ReadAndParse {


    public static void main(String[] args) throws ParserConfigurationException,
                                                  SAXException, IOException {
        File inputFile = new File("File Location");
        DocumentBuilderFactory dbfact = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbfact.newDocumentBuilder();
        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();
        NodeList list = doc.getDocumentElement().getChildNodes();
        //Set with node names
        Set<String> nodeSet = new LinkedHashSet<String>();
        nodeSet = getAllNodeName(list,nodeSet); 
        //Printing node name
        for(String node : nodeSet){
            System.out.println(node);
        }
    }

    private static Set<String> getAllNodeName(NodeList list,Set<String> nodeSet) {
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getNodeType() == node.ELEMENT_NODE && node.getNodeType() != node.COMMENT_NODE) {
                nodeSet.add(node.getNodeName());
                if(node.getChildNodes().getLength() > 1){
                    nodeSet = getAllNodeName(node.getChildNodes(),nodeSet);
                }
            }
        }
        return nodeSet;
    }
}


Output :

NAME
AGE
ADDRESS
CITY
STATE

*Comments and feedback are most welcomed, Thanks.

No comments:

Post a Comment