DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Java - Dom Parser Example

02.23.2007
| 142273 views |
  • submit to reddit
        // Simple Parser XML with DOM

package parser;

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

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 DOMParser
{
	private Document doc = null;
	
	public DOMParser()
	{
		try
		{
			doc = parserXML(new File("parser/file.xml"));
			
			visit(doc, 0);
		}
		catch(Exception error)
		{
			error.printStackTrace();
		}
	}
	
	public void visit(Node node, int level)
	{
		NodeList nl = node.getChildNodes();
		
		for(int i=0, cnt=nl.getLength(); i<cnt; i++)
		{
			System.out.println("["+nl.item(i)+"]");
			
			visit(nl.item(i), level+1);
		}
	}
	
	public Document parserXML(File file) throws SAXException, IOException, ParserConfigurationException
	{
		return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
	}
	
	public static void main(String[] args)
	{
		new DOMParser();
	}
}
    

Comments

chandan ma replied on Fri, 2009/12/18 - 4:17pm

you can get node directly chandan

Sharad Sharma replied on Tue, 2007/10/23 - 12:09am

can any one please tell me how to get the data of a specific node using DOM parser say i have a node ABC and i want to get ABC only how to do that