Read XML File using SAX Parser in JAVA

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 1 Comment on Read XML File using SAX Parser in JAVA

Example of Reading XML File using SAX Parser in JAVA

We have already discussed about the DOM Parser of JAXP. This article will focus on Reading XML file using SAX Parser:

SAX Parser
SAX Parser

SAXParser object can obtained from the SAXParserFactory and then we can process the document using that parser.
The most important interface in SAX parser class is ContentHandler. This interface requires a number of methods that the SAX parser invokes in response to various parsing events. The major event-handling methods are: startDocument, endDocument, startElement, and endElement.
The easiest way to implement this interface is to extend the DefaultHandler class, defined in the org.xml.sax.helpers package. That class provides do-nothing methods for all the ContentHandler events.

The example program extends that class.
public class SAXLocalNameCount extends DefaultHandler {

Example :

Locator to indicate the current position of SAX Parser.

package com.G2.SAX;


import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMlParserLocator extends DefaultHandler {
	Locator locator;

	public void startElement(String uri, String localName, String tagName, Attributes arg3) throws SAXException {
		String locationString = "";
		if (locator != null) {
			locationString += locator.getSystemId();
			locationString += "Line : " + locator.getLineNumber();
			locationString += "Column : " + locator.getColumnNumber();


	public static void main(String[] args) {

		try {
			SAXParserFactory saxFactory = SAXParserFactory.newInstance();
			SAXParser parser = saxFactory.newSAXParser();
			parser.parse("ShivaSoft.xml", new XMlParserLocator());

		} catch (ParserConfigurationException e) {
		} catch (SAXException e) {
		} catch (IOException e) {

	public void setDocumentLocator(Locator arg0) {
		locator = arg0;
		System.out.println("setDocumentLocator() Called");


Related posts

  • a