Read 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 java.io.IOException;

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;

	@Override
	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();
			System.out.println(locationString);

		}
	}

	public static void main(String[] args) {

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

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

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

}

Posted

in

by

Tags:


Related Posts

Comments

One response to “Read XML File using SAX Parser in JAVA”

  1. a Avatar
    a

    aa

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading