SAX

Parse XML file with SAX

With this example we are going to demonstrate how to parse an XML file with SAX. Simple API for XML (SAX) is an event-driven, serial-access mechanism for accessing XML documents. It is frequently used by servlets and network-oriented programs that need to transmit and receive XML documents, because it is the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents, other than the Streaming API for XML (StAX). We have created a Class, ParseXMLFileWithSAX that is a handler that extends the DefaultHandler and overrides its startElement(String uri, String localName, String qName, Attributes attributes) and endElement(String uri, String localName, String qName) API methods. The basic steps of the example are described below:

  • Create a new instance of the ParseXMLFileWithSAX class.
  • Obtain a new instance of a SAXParserFactory, that is a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
  • Set the parser produced by this code so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of SAXParserFactory with validating set to false.
  • Create a new instance of a SAXParser, using newSAXParser() API method of SAXParserFactory.
  • Use parse(File f, DefaultHandler dh) API method of SAXParser to parse the content of the specified XML file, using the specified handler of the example.
  • The ParseXMLFileWithSAX class of the example overrides startElement(String uri, String localName, String qName, Attributes attributes) and endElement(String uri, String localName, String qName) API methods of DefaultHandler. For example it can append to a buffer the attributes of the Element and when it reaches to the end of the element it can print the results.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

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 ParseXMLFileWithSAX extends DefaultHandler {
	
private StringBuffer buffer = new StringBuffer();
	
	private static String responseCode;
	private static String date;
	private static String title;
	
	private static Currency currency;
	private static Rates rates;
	
	public static void main(String[] args) throws Exception {
		
		DefaultHandler handler = new ParseXMLFileWithSAX();

		SAXParserFactory factory = SAXParserFactory.newInstance();

  factory.setValidating(false);

  

  SAXParser parser = factory.newSAXParser();

  

  parser.parse(new File("in.xml"), handler);

  

  System.out.println("Response Code:" + responseCode);

  System.out.println("Date:" + date);

  System.out.println("Title:" + title);

  System.out.println("Rates:");

  

  for (Currency curr : rates.currencies) {
			System.out.println("tCode:" + curr.code + " - Rate:" + curr.rate);
		}
		
	}
	
	private static class Currency {
		public String code;
		public String rate;
	}
	
	private static class Rates {
		public List<Currency> currencies = new LinkedList<Currency>();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		buffer.setLength(0);
		
		if (qName.equals("response")) {
			responseCode = attributes.getValue("code");
		}
		else if (qName.equals("date")) {
			date = "";
		}
		else if (qName.equals("title")) {
			title = "";
		}
		else if (qName.equals("rates")) {
			rates = new Rates(); 
		}
		else if (qName.equals("currency")) {
			currency = new Currency(); 
		}
		
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)throws SAXException {
		
		if (qName.equals("date")) {
			date = buffer.toString();
		}
		else if (qName.equals("title")) {
			title = buffer.toString();
		}
		else if (qName.equals("currency")) {
			rates.currencies.add(currency);
		}
		else if (qName.equals("code")) {
			currency.code = buffer.toString();
		}
		else if (qName.equals("rate")) {
			currency.rate = buffer.toString();
		}
		
	}
	
    public void characters(char[] ch, int start, int length) {
		buffer.append(ch, start, length);
	}

}

Input:

<?xml version="1.0" encoding="UTF-8" ?>
<response code="200">
	<date>2008-11-07</date>
	<title>Exchange rates for 2008-11-07</title>
	<rates>
		<currency>
			<code>EUR</code>
			<rate>1.220</rate>
		</currency>
		<currency>
			<code>USD</code>
			<rate>1.275</rate>
		</currency>
	</rates>
</response>

Output:

Response Code:200
Date:2008-11-07
Title:Exchange rates for 2008-11-07
Rates:
	Code:EUR - Rate:1.0
	Code:USD - Rate:1.275600

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button