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:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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;
 
  }
 
    }
 
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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;
    }
 
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
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;
 
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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;
    }   
 
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
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:

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
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 the Terms and Privacy Policy

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