Parser

Published on February 2017 | Categories: Documents | Downloads: 24 | Comments: 0 | Views: 225
of 5
Download PDF   Embed   Report

Comments

Content

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

Doesn’t 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.*;

doesn’t 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 doesn’t 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.
That’s all on difference between SAX and DOM parsers in Java, now it’s 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 don’t 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");
}
}

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close