Parse XML file with DOM

This is an example of how to parse an xml file using a DOM Document. The DOM Document interface represents the entire HTML or XML document and provides the primary access to a document’s data. Parsing an xml file using a DOM Document implies that you should:

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

package com.javacodegeeks.snippets.core;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXMLFileWithDOM {
	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	DocumentBuilder db = dbf.newDocumentBuilder();
    	Document doc = db.parse(new FileInputStream(new File("in.xml")));
    	Element channelNode = (Element) doc.getElementsByTagName("channel").item(0);
    	Node titleNode = channelNode.getElementsByTagName("title").item(0);
    	String title = titleNode.getFirstChild().getNodeValue();
    	System.out.println("Title: " + title);
    	Node languageNode = channelNode.getElementsByTagName("language").item(0);
    	String language = languageNode.getFirstChild().getNodeValue();
    	System.out.println("Language: " + language);
    	NodeList itemsList = doc.getElementsByTagName("item");
    	int itemsCount = itemsList.getLength();
    	for (int i = 0; i<itemsCount; i++) {	
    		System.out.println("Item: ");
    		Node itemNode = itemsList.item(i);
			Element item = (Element) itemNode;
			Node itemTitleNode = item.getElementsByTagName("title").item(0);
			String itemTitle = itemTitleNode.getFirstChild().getNodeValue();
	    	System.out.println("tTitle: " + itemTitle);			
			Node linkNode = item.getElementsByTagName("link").item(0);
			String link = linkNode.getFirstChild().getNodeValue();
	    	System.out.println("tLink: " + link);		
			Node pubDateNode = item.getElementsByTagName("pubDate").item(0);
			String pubDate = pubDateNode.getFirstChild().getNodeValue();
	    	System.out.println("tPubDate: " + pubDate);


<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
		<title>Java Tutorials and Examples</title>
			<title><![CDATA[Java Tutorials]]></title>
			<pubDate>Sun, 16 Nov 2008 23:25:02 -0600</pubDate>
			<title><![CDATA[Java Examples]]></title>
			<pubDate>Sun, 16 Nov 2008 23:25:02 -0600</pubDate>


Title: Java Tutorials and Examples
Language: en-us
	Title: Java Tutorials
	PubDate: Sun, 16 Nov 2008 23:25:02 -0600
	Title: Java Examples
	PubDate: Sun, 16 Nov 2008 23:25:02 -0600

This was an example of how to parse an xml file using a DOM Document in Java.

Exit mobile version