0% found this document useful (0 votes)
17 views3 pages

Dom Parser

Uploaded by

Vignesh S CSE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views3 pages

Dom Parser

Uploaded by

Vignesh S CSE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Ex-10

Parsing XML document using DOM parser

Parser.java

package loginservlet;

import java.io.File;

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 parser {

public static void main(String args[]) {

try {

File shiporder = new File("C:\\Users\\nitro\\eclipse-


workspace\\loginservlet\\webContent\\NewFile.xml");

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(shiporder);

doc.getDocumentElement().normalize();

System.out.println("root of xml file" +


doc.getDocumentElement().getNodeName());

NodeList nodes = doc.getElementsByTagName("shipto");

System.out.println("==========================");

for (int k = 0; k < nodes.getLength(); k++) {

Node node = nodes.item(k);

if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;

System.out.println("Name: " + getValue("name", element));

System.out.println("Address: " + getValue("address", element));

System.out.println("City: " + getValue("city", element));

System.out.println("Country: " + getValue("country", element));

nodes=doc.getElementsByTagName("item");

for (int k = 0; k < nodes.getLength(); k++) {

Node node = nodes.item(k);

if (node.getNodeType() == Node.ELEMENT_NODE) {

Element element = (Element) node;

System.out.println("Title: " + getValue("title", element));

if(getValue("note", element)!=null)

System.out.println("Note: " + getValue("note", element));

System.out.println("Quantity: " + getValue("quantity", element));

System.out.println("Price: " + getValue("price", element));

catch (Exception ex) {

ex.printStackTrace();

private static String getValue(String tag, Element element) {

NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();

Node node = (Node) nodes.item(0);

return node.getNodeValue();

}
}

You might also like