xml

Parsing XML with SAX

In this tutorial we are going to see how can we parse an XML file using the SAX parsing method.

The SAX specification reads through the XML Document and uses events and callback handlers to perform the parsing. It’s a bit more challenging than other methods, DOM for example, but it’s flexible and much more memory efficient.

The basic steps to perform SAX Parsing to an XML Document are:

  • First of all create the appropriate model classes to map the XML entities to Java classes
  • Create an new instace of SAXParserFactory
  • Use the appropriate handlers to hand the events of the parsing process by extending the DefaultHandler class
  • Create the appropriate callback functions to handle the events, e.g. when a new element is found
Let’s take a look at the code:
package com.javacodegeeks.android.apps.moviesearchapp.services;

import java.io.StringReader;
import java.util.ArrayList;

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

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.javacodegeeks.android.apps.moviesearchapp.handlers.MovieHandler;
import com.javacodegeeks.android.apps.moviesearchapp.handlers.PersonHandler;
import com.javacodegeeks.android.apps.moviesearchapp.model.Movie;
import com.javacodegeeks.android.apps.moviesearchapp.model.Person;

public class XmlParser {

    private XMLReader initializeReader() throws ParserConfigurationException, SAXException {

  SAXParserFactory factory = SAXParserFactory.newInstance();

  // create a parser

  SAXParser parser = factory.newSAXParser();

  // create the reader (scanner)

  XMLReader xmlreader = parser.getXMLReader();

  return xmlreader;
    }

    public ArrayList<Person> parsePeopleResponse(String xml) {

  try {

XMLReader xmlreader = initializeReader();

PersonHandler personHandler = new PersonHandler();

// assign our handler

xmlreader.setContentHandler(personHandler);

// perform the synchronous parse

xmlreader.parse(new InputSource(new StringReader(xml)));

return personHandler.retrievePersonList();

  } 

  catch (Exception e) {

e.printStackTrace();

return null;

  }

    }

    public ArrayList<Movie> parseMoviesResponse(String xml) {

  try {

XMLReader xmlreader = initializeReader();

MovieHandler movieHandler = new MovieHandler();

// assign our handler

xmlreader.setContentHandler(movieHandler);

// perform the synchronous parse

xmlreader.parse(new InputSource(new StringReader(xml)));

return movieHandler.retrieveMoviesList();

  } 

  catch (Exception e) {

e.printStackTrace();

return null;

  }

    }

}
package com.javacodegeeks.android.apps.moviesearchapp.handlers;

import java.util.ArrayList;

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

import com.javacodegeeks.android.apps.moviesearchapp.model.Image;
import com.javacodegeeks.android.apps.moviesearchapp.model.Person;

public class PersonHandler extends DefaultHandler {

    private StringBuffer buffer = new StringBuffer();

    private ArrayList<Person> personList;
    private Person person;
    private ArrayList<Image> personImagesList;
    private Image personImage;

    @Override
    public void startElement(String namespaceURI, String localName,

String qName, Attributes atts) throws SAXException {

  buffer.setLength(0);

  if (localName.equals("people")) {

personList = new ArrayList<Person>();

  }

  else if (localName.equals("person")) {

person = new Person();

  }

  else if (localName.equals("images")) {

personImagesList = new ArrayList<Image>();

  }

  else if (localName.equals("image")) {

personImage = new Image();

personImage.type = atts.getValue("type");

personImage.url = atts.getValue("url");

personImage.size = atts.getValue("size");

personImage.width = Integer.parseInt(atts.getValue("width"));

personImage.height = Integer.parseInt(atts.getValue("height"));

  }

    }

    @Override
    public void endElement(String uri, String localName, String qName)throws SAXException {

  if (localName.equals("person")) {

personList.add(person);

  }

  else if (localName.equals("score")) {

person.score = buffer.toString();

  }

  else if (localName.equals("popularity")) {

person.popularity = buffer.toString();

  }

  else if (localName.equals("name")) {

person.name = buffer.toString();

  }

  else if (localName.equals("id")) {

person.id = buffer.toString();

  }

  else if (localName.equals("biography")) {

person.biography = buffer.toString();

  }

  else if (localName.equals("url")) {

person.url = buffer.toString();

  }

  else if (localName.equals("version")) {

person.version = buffer.toString();

  }

  else if (localName.equals("last_modified_at")) {

person.lastModifiedAt = buffer.toString();

  }    

  else if (localName.equals("image")) {

personImagesList.add(personImage);

  }    

  else if (localName.equals("images")) {

person.imagesList = personImagesList;

  }

    }

    @Override
    public void characters(char[] ch, int start, int length) {

  buffer.append(ch, start, length);
    }

    public ArrayList<Person> retrievePersonList() {

  return personList;
    }

}
package com.javacodegeeks.android.apps.moviesearchapp.model;

import java.util.ArrayList;

public class Person {

    public String score;
    public String popularity;
    public String name;
    public String id;
    public String biography;
    public String url;
    public String version;
    public String lastModifiedAt;
    public ArrayList<Image> imagesList;

}
package com.javacodegeeks.android.apps.moviesearchapp.model;

import java.util.ArrayList;

public class Movie {

    public String score;
    public String popularity;
    public boolean translated;
    public boolean adult;
    public String language;
    public String originalName;
    public String name;
    public String type;
    public String id;
    public String imdbId;
    public String url;
    public String votes;
    public String rating;
    public String certification;
    public String overview;
    public String released;
    public String version;
    public String lastModifiedAt;
    public ArrayList imagesList;

    public String retrieveThumbnail() {

  if (imagesList!=null && !imagesList.isEmpty()) {

for (Image movieImage : imagesList) {

    if (movieImage.size.equalsIgnoreCase(Image.SIZE_THUMB) &&

movieImage.type.equalsIgnoreCase(Image.TYPE_POSTER)) {

  return movieImage.url;

    }

}

  }

  return null;
    }    

}
package com.javacodegeeks.android.apps.moviesearchapp.model;

public class Image {

    public static final String SIZE_ORIGINAL = "original";
    public static final String SIZE_MID = "mid";
    public static final String SIZE_COVER = "cover";
    public static final String SIZE_THUMB = "thumb";

    public static final String TYPE_PROFILE = "profile";
    public static final String TYPE_POSTER = "poster";

    public String type;
    public String url;
    public String size;
    public int width;
    public int height;

}

 
This was an example of how to perform SAX parsing of an XML Document in Android.

Related Article:

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button