Saturday 12, Apr 2025
We are moved to new domain
Click -> www.ehowtonow.com
Saturday, 9 November 2013

Read XML File using DOM parser


In this tutorial we are going to see how to read XML file using DOM Parser. In this example I used to read XML document by Element Name.
DOM parser parse the entire XML document and load it into memory.DOM parse the nodes as tree structure which is easy for traversal or manipulation.
DOM parser slow compare to other parsers and it consumes lot of memory.You can use SAX parser instead of DOM.SAX parser if faster than DOM and uses less memory.
1. Create Project Called JavaXML.
2. Create package called com.javatutorialscorner.xml.dom under JavaXML.
3. Create Java class called ReadXMLFile.java under com.javatutorialscorner.xml.dom package.
ReadXMLFile.java
01.package com.javatutorialscorner.xml.dom;
02. 
03.import java.io.File;
04.import java.io.IOException;
05. 
06.import javax.xml.parsers.DocumentBuilder;
07.import javax.xml.parsers.DocumentBuilderFactory;
08.import javax.xml.parsers.ParserConfigurationException;
09. 
10.import org.w3c.dom.Document;
11.import org.w3c.dom.Element;
12.import org.w3c.dom.Node;
13.import org.w3c.dom.NodeList;
14.import org.xml.sax.SAXException;
15. 
16.public class ReadXMLFile {
17. 
18. /**
19.  * @param args
20.  */
21. public static void main(String[] args) {
22.  // TODO Auto-generated method stub
23. 
24.  try {
25.   File xmlFile = new File("C:\\jtc\\student.xml");
26.   DocumentBuilderFactory builderFactory = DocumentBuilderFactory
27.     .newInstance();
28.   DocumentBuilder builder = builderFactory.newDocumentBuilder();
29.   Document document = builder.parse(xmlFile);
30.   document.getDocumentElement().normalize();
31.   System.out.println("Root Node :"
32.     + document.getDocumentElement().getNodeName());
33.   NodeList list = document.getElementsByTagName("student");
34.   for (int i = 0; i < list.getLength(); i++) {
35.    Node node = list.item(i);
36.    System.out.println("***********************");
37.    System.out.println("Child Element : " + node.getNodeName());
38. 
39.    if (node.getNodeType() == Node.ELEMENT_NODE) {
40.     Element element = (Element) node;
41.     System.out.println("Student ID : "
42.       + element.getAttribute("id"));
43.     System.out.println("First Name : "
44.       + element.getElementsByTagName("firstname").item(0)
45.         .getTextContent());
46.     System.out.println("Last Name : "
47.       + element.getElementsByTagName("lastname").item(0)
48.         .getTextContent());
49.     System.out.println("Department : "
50.       + element.getElementsByTagName("department")
51.         .item(0).getTextContent());
52.     System.out.println("***********************");
53.    }
54. 
55.   }
56.  } catch (ParserConfigurationException e) {
57.   // TODO Auto-generated catch block
58.   e.printStackTrace();
59.  } catch (SAXException e) {
60.   // TODO Auto-generated catch block
61.   e.printStackTrace();
62.  } catch (IOException e) {
63.   // TODO Auto-generated catch block
64.   e.printStackTrace();
65.  }
66. 
67. }
68. 
69.}

In above program document.getDocumentElement().normalize(); is option element but its recommended.Consider the following XML tag

<firstname>Shiva

Kumar</firstname>

 which is denormalized as follows

Element firstname

Text node : “”

Text node : “Shiva”

Text node : “Kumar”

Text node : “”

When its is normalized

Element firstname

Text node : “Shiva Kumar”

XML File

student.xml

01.<?xml version="1.0" encoding="UTF-8"?>
02.<college>
03.<student id="1">
04.<firstname>Shiva</firstname>
05.<lastname>Kumar</lastname>
06.<department>ECE</department>
07.</student>
08.<student id="2">
09.<firstname>Appu</firstname>
10.<lastname>T</lastname>
11.<department>CSE</department>
12.</student>
13.</college>

Now you can run the program see the following output in console.

Root Node :college

***********************

Child Element : student

Student ID : 1

First Name : Shiva

Last Name : Kumar

Department : ECE

***********************

***********************

Child Element : student

Student ID : 2

First Name : Appu

Last Name : T

Department : CSE

***********************

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer

Related Posts:

  • Java 8 – Overview and New Features Java 8 (Java SE 8) is a major feature release.With Java 8 release, java provided support for Functional Programming JavaScript Engine API for Date and Time Streaming API, etc.., New Features in Java 8 Some important featu… Read More
  • How to get file size using Java Following example shows how to get file size in bytes using file.length() method in Java. lengthpublic long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this … Read More
  • How to convert a String to Upper caseFollowing example shows how to convert a string to upper case. Sample Programpackage com.javatutorialcorner.javastring;public class ToUpperCase { public static void main(String[] args) { String input = "Java tutoria… Read More
  • How to delete file using Java Following example shows how to delete file using file.delete() method in Java. delete public boolean delete() Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the … Read More
  • How to compare paths of two file using Java Following example shows how to compare paths of two file using file1.compareTo() method in Java. compareTo public int compareTo(File pathname)  Compares two abstract pathnames lexicographically. The ordering defined by… Read More
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Read XML File using DOM parser Rating: 5 Reviewed By: eHowToNow