Simple DOM example Java

1. The DOM parser example:

package com.vvirlan;
import java.io.File;
import java.io.IOException;
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 DomExample {
	public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
		DomExample ex = new DomExample();
		ex.run();
	}

	public void run() throws SAXException, IOException, ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		// factory.setValidating(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new File("C:\\tmp\\myxml.xml"));
		NodeList nodeList = doc.getElementsByTagName("name");
		Node firstNode = nodeList.item(0);
		System.out.println(firstNode.getNodeName() + " = " + firstNode.getTextContent());
	}
}

2. The XML file

<?xml version="1.0" encoding="UTF-8"?>
<records>
	<record>
		<name>Queen I</name>
		<year>1988</year>
		<artist>Queen</artist>
	</record>
		<record>
		<name>Reloaded</name>
		<year>1992</year>
		<artist>Metallica</artist>
	</record>
</records>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s