Simple DOM example Java

1. The DOM parser example:

package com.vvirlan;
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();;

	public void run() throws SAXException, IOException, ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 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"?>
		<name>Queen I</name>

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s