DOM

Visit nodes in DOM document recursively

With this example we are going to demonstrate how to visit recursively the nodes in a DOM Document. We have implemented a method void visitRecursively(Node node), in order to visit a node and its children in the DOM Document. In short, to visit recursively the nodes in a DOM Document you should:

  • Obtain a new instance of a DocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
  • Set the parser produced so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of DocumentBuilderFactory, with validating set to false.
  • Create a new instance of a DocumentBuilder, using newDocumentBuilder() API method of DocumentBuilderFactory.
  • Parse the FileInputStream with the content to be parsed, using parse(InputStream is) API method of DocumentBuilder. This method parses the content of the given InputStream as an XML document and returns a new DOM Document object.
  • Call visitRecursively(Node node) method of the example, with the given document as parameter. The method gets the NodeList that contains all children of this node, using getChildNodes() API method of Node. For each one of the nodes in the nodeList it gets its name and the value, using getNodeName() and getNodeValue() API methods of Node. Then it begins the same steps for the specified node, to get the children of this node.

Let’s take a look at the code snippet that follows: 

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;

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

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

public class VisitNodesInDOMDocumentRecursively {
	
	public static void main(String[] args) throws Exception {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);
		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc = db.parse(new FileInputStream(new File("in.xml")));
		
		visitRecursively(doc);
		
	}
	
	public static void visitRecursively(Node node) {

	    // get all child nodes
	    NodeList list = node.getChildNodes();
	    
	    for (int i=0; i<list.getLength(); i++) {
	
  
	    	// get child node
	
  Node childNode = list.item(i);
	
  
	
  System.out.println("Found Node: " + childNode.getNodeName()
	
  		+ " - with value: " + childNode.getNodeValue());

	
  // visit child node
	
  visitRecursively(childNode);
	    }
	    
	}

}

Input:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples</title>
		<language>en-us</language>
		<item>
			<title><![CDATA[Java Tutorials]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
		<item>
			<title><![CDATA[Java Examples]]></title>
			<link>http://examples.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>

Output:

Found Node: rss - with value: null
Found Node: #text - with value: 
	
Found Node: channel - with value: null
Found Node: #text - with value: 
		
Found Node: title - with value: null
Found Node: #text - with value: Java Tutorials and Examples
Found Node: #text - with value: 
		
Found Node: language - with value: null
Found Node: #text - with value: en-us
Found Node: #text - with value: 
		
Found Node: item - with value: null
Found Node: #text - with value: 
			
Found Node: title - with value: null
Found Node: #cdata-section - with value: Java Tutorials
Found Node: #text - with value: 
			
Found Node: link - with value: null
Found Node: #text - with value: http://www.javacodegeeks.com/
Found Node: #text - with value: 
		
Found Node: #text - with value: 
		
Found Node: item - with value: null
Found Node: #text - with value: 
			
Found Node: title - with value: null
Found Node: #cdata-section - with value: Java Examples
Found Node: #text - with value: 
			
Found Node: link - with value: null
Found Node: #text - with value: http://examples.javacodegeeks.com/
Found Node: #text - with value: 
		
Found Node: #text - with value: 
	
Found Node: #text - with value: 

  
This was an example of how to visit recursively the nodes in a DOM Document in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button