SAX Generally Runs A Little Faster Than DOM SAX Generally Runs A Little Faster Than DOM

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 5

SAX

DOM

Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages
and can be used in our programming depending on the situation.
Parses node by node

Stores the entire XML document into memory


before processing

Doesnt store the XML in memory

Occupies more memory

We cant insert or delete a node

We can insert or delete nodes

Top to bottom traversing

Traverse in any direction.

SAX is an event based parser

DOM is a tree model parser

SAX is a Simple API for XML

Document Object Model (DOM) API

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;

doesnt preserve comments

preserves comments

SAX generally runs a little faster than DOM

SAX generally runs a little faster than DOM

If we need to find a node and doesnt need to insert or delete we can go with SAX itself otherwise
DOM provided we have more memory.
Here are few high level differences between DOM parser and SAX Parser in Java:
1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.
2) DOM parser is faster than SAX because it access whole XML document in memory.
3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much
memory.
4) DOM parser works on Document Object Model while SAX is an event based xml parser.
Thats all on difference between SAX and DOM parsers in Java, now its up to you on which XML parser you
going to choose. I recommend use DOM parser over SAX parser if XML file is small enough and go with SAX
parser if you dont know size of xml files to be processed or they are large.

Parsing XML Files with SAX


/*
<PHONEBOOK>
<PERSON>
<NAME>Joe Wang</NAME>
<EMAIL>[email protected]</EMAIL>
<TELEPHONE>202-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Karol</name>
<EMAIL>[email protected]</EMAIL>
<TELEPHONE>306-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Green</NAME>
<EMAIL>[email protected]</EMAIL>
<TELEPHONE>202-414-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
</PHONEBOOK>
*/
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class NameLister {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Usage: java NameLister xmlfile.xml");
System.exit(-1);
}
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {

boolean name = false;


public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (name) {
System.out.println("Name: "
+ new String(ch, start, length));
name = false;
}
}
};
saxParser.parse(args[0], handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>

package net.viralpatel.java.xmlparser;
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 XMLParser {
public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());
NodeList studentList =
docEle.getElementsByTagName("student");
// Print total student elements in document
System.out
.println("Total students: " +
studentList.getLength());
if (studentList != null && studentList.getLength() >
0) {
for (int i = 0; i < studentList.getLength(); i++)
{
Node node = studentList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE)
{
System.out
.println("=====================")
;
Element e = (Element) node;
NodeList nodeList =
e.getElementsByTagName("name");
System.out.println("Name: "
+
nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList =
e.getElementsByTagName("grade");
System.out.println("Grade: "
+
nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "
+
nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}

You might also like