sax xml parser in java

The SAX stands for the “Simple API for XML”. Unlike a DOM parser which loads document in the memory, SAX s an event-based parse. It works on the events when an event occur it calls some callback methods. The parse() method of the SAXParser will starts the XML processing.

SAX is push API:

As we discussed above SAX parser works on the events when an event occur it calls handler object methods. For example, SAX parser encounters an event of the beginning of an XML element, it will call the startElement on handler object. As it pushes the information from XML to handler object that why it is known as push style API.
Note: As SAX parser not loads the complete document in the memory it uses less memory and faster than DOM parser.
Limitation: We can only read and can’t write the XML documents using SAX parser. It only process the XML document from top to bottom and not provide the random access facility.

SAX parser works on following events:

1. startDocument
2. startElement
3. characters
4. comments
5. processing instructions
6. endElement
7. endDocument

Commonly Used methods of SAX XML Parser:

1. startDocument(): It is called at the beginning of the xml document.
2. endDocument(): It is called at the end of the xml document.
3. startElement(String uri, String localName, String qName, Attributes atts): It is called at the beginning of an element.
4. endElement(String uri, String localName,String qName): It is called at the end of an element.
5. characters(char[] ch, int start, int length): It is called when text data is encountered between start and end tags of an element.

Example:

classInfo.xml
<?xml version="1.0"?>
<class>
<student rollNo="1">
<firstName>Prabhjot</firstName>
<lastName>Kaur</lastName>
<marks>85</marks>
</student>
<student rollNo="2">
<firstName>Nidhi</firstName>
<lastName>Gupta</lastName>
<marks>88</marks>
</student>
</class>
SAXParserTest.java
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
/**
* This class is used to read XML elements using SAX parser.
* @author javawithease
*/

public class SAXParserTest {
public static void main(String[] args){
try {
//File Path
String filePath = "D:\\classInfo.xml";
 
//Create file object.
File inputFile = new File(filePath);
 
//Get SAXParserFactory instance.
SAXParserFactory factory=SAXParserFactory.newInstance();
 
//Get SAXParser object from SAXParserFactory instance.
SAXParser saxParser = factory.newSAXParser();
 
//Create StudentHandler object.
StudentHandler studentHandler = new StudentHandler();
 
//Parse the XML file.
saxParser.parse(inputFile, studentHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
StudentHandler.java
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
/**
* This class implements the SAX DefaultHandler events.
* @author javawithease
*/

class StudentHandler extends DefaultHandler {
boolean isFirstName = false;
boolean isLastName = false;
boolean isMarks = false;
 
@Override
public void startElement(String uri,
String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("student")) {
String rollNo = attributes.getValue("rollNo");
System.out.println("Roll No : " + rollNo);
} else if (qName.equalsIgnoreCase("firstName")) {
isFirstName = true;
} else if (qName.equalsIgnoreCase("lastName")) {
isLastName = true;
} else if (qName.equalsIgnoreCase("marks")) {
isMarks = true;
}
}
 
@Override
public void endElement(String uri,
String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("student")) {
System.out.println("End Element:" + qName);
}
}
 
@Override
public void characters(char ch[],
int start, int length) throws SAXException {
if (isFirstName) {
System.out.println("First Name: "
+ new String(ch, start, length));
isFirstName = false;
} else if (isLastName) {
System.out.println("Last Name: "
+ new String(ch, start, length));
isLastName = false;
} else if (isMarks) {
System.out.println("Marks: "
+ new String(ch, start, length));
isMarks = false;
}
}
}

Output:

Roll No : 1
First Name: Prabhjot
Last Name: Kaur
Marks: 85
End Element:student
Roll No : 2
First Name: Nidhi
Last Name: Gupta
Marks: 88
End Element:student

No comments: