SAX

Parse XML file with SAX

Photo of Byron KiourtzoglouByron KiourtzoglouNovember 11th, 2012Last Updated: July 2nd, 2013
0 91 2 minutes read

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 theDefaultHandler and overrides itsstartElement(String uri, String localName, String qName, Attributes attributes) andendElement(String uri, String localName, String qName) API methods. The basic steps of the example are described below:

  • Create a new instance of theParseXMLFileWithSAX class.
  • Obtain a new instance of aSAXParserFactory, 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, usingsetValidating(boolean validating) API method of SAXParserFactory with validating set to false.
  • Create a new instance of aSAXParser, usingnewSAXParser() API method of SAXParserFactory.
  • Useparse(File f, DefaultHandler dh) API method of SAXParser to parse the content of the specified XML file, using the specified handler of the example.
  • TheParseXMLFileWithSAX class of the example overridesstartElement(String uri, String localName, String qName, Attributes attributes) andendElement(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>();}@Overridepublic 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(); }}@Overridepublic 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:200Date:2008-11-07Title:Exchange rates for 2008-11-07Rates:Code:EUR - Rate:1.0Code:USD - Rate:1.275600
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Byron KiourtzoglouByron KiourtzoglouNovember 11th, 2012Last Updated: July 2nd, 2013
0 91 2 minutes read
Photo of Byron Kiourtzoglou

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 atJava Code Geeks.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.