Wednesday, 19 September 2012

Java XML DOM Parser Reading XML Example



DOM Parser classes

DocumentBuilder –> This class defines the API to obtain DOM Document instances from an XML document.
DocumentBuilderFactory –> Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
Document->The Document interface represents the entire HTML or XML document.
Element –>The Element interface represents an element in an HTML or XML document.
Node –> The Node interface is the primary datatype for the entire Document Object Model.
NodeList –>The NodeList interface provides the abstraction of an ordered collection of nodes.

DOM XML Reading Example

Sample xml file (orderdetails.xml)


<Ordernumber Number="9988">
<Ordernumber Number="9999">

Java Program to read xml

package mycollectiontest;

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

public static void main(String[] args) {
try {
File fXmlFile = new File("orderdetails.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
System.out.println("Order Details" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Ordernumber");

for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Node orderedItem1 = (Node) (NodeList) eElement.getElementsByTagName("OrderedItem1")
System.out.println("OrderedItem1 :" + orderedItem1.getNodeValue());

Node orderitemPrice = (Node) (NodeList) eElement.getElementsByTagName("OrderitemPrice")
System.out.println("OrderitemPrice :" + orderitemPrice.getNodeValue());
Node orderitemTax = (Node) (NodeList) eElement.getElementsByTagName("OrderitemTax")
System.out.println("OrderitemTax :" + orderitemTax.getNodeValue());
Node orderDiscount = (Node) (NodeList) eElement.getElementsByTagName("OrderDiscount")
System.out.println("OrderDiscount :" + orderDiscount.getNodeValue());
} catch (Exception e) {



Order DetailsOrder
OrderedItem1 :Pepsi
OrderitemPrice :10
OrderitemTax :10
OrderDiscount :20
OrderedItem1 :Cocacola
OrderitemPrice :11
OrderitemTax :11
OrderDiscount :22