View RSS Feed

My Java Tips

Parsing XML Documents-1 (DOM and SAX)

Rate this Entry
by , 11-10-2011 at 04:03 PM (1462 Views)
XML files are very useful. Usually they are used to store configuration settings. We can also use XML files to store data so it can be used as a database. A lot of work has been done in this domain and its really very useful working with XML files.

Now suppose you have a XML file with some useful data.

XML Code:
We need to parse and get the data from xml file. We have a class called Student with first, last and age attributes. These attributes are declared private and we have public getter/setters. We want to get data from XML document and save the data to Java objects.

Java Code:
public class Student {
private String first;
private String last;
private int age;
public String getFirst() {
	return first;
public void setFirst(String first) {
	this.first = first;
public String getLast() {
	return last;
public void setLast(String last) {
	this.last = last;
public int getAge() {
	return age;
public void setAge(int age) {
	this.age = age;
One was is to create a File object and then use BufferedReader to read the file. Then we can use StringTokenizer to search for the required tokens and we can get the required text.

This way will work but Java provides a better way to parse XML documents. We can use DOM (Document Object Model) or SAX (Simple API for XML) to parse the XML file in an efficient way.

DOM parser creates a tree in memory to represent XML document so it takes a lot me memory. Even of you want to get data from one tag, whole file will be mapped to a tree in the memory. SAX parses the element as node in encountered.

Submit "Parsing XML Documents-1 (DOM and SAX)" to Facebook Submit "Parsing XML Documents-1 (DOM and SAX)" to Digg Submit "Parsing XML Documents-1 (DOM and SAX)" to Submit "Parsing XML Documents-1 (DOM and SAX)" to StumbleUpon Submit "Parsing XML Documents-1 (DOM and SAX)" to Google

Tags: dom parser, sax, xml Add / Edit Tags
Java SE