Android SAX Parser Example From Url

This example will show you how to use SAXParserFactory and SAXParser to parse a xml file from a url. All above class is included in package javax.xml.parsers

android sax parser example from url

This example is based on Android Parse Xml Use XmlPullParser Example. It just add a button. When click this button, it will read the xml data from same url and use SAX parser to parse it and display the parse result in bottom text view.

1. SAX Parser Working Diagram.

SAX parser is something different from XmlPullParser. It will parse the xml document from first element to the last element in order.

java xml sax parser theory

To use sax parser, you need to create a custom content handler class. This class should extends org.xml.sax.helpers.DefaultHandler.

You should override the methods in DefaultHandler class which you need. Such as startElement, endElement, characters etc. Those methods are easy to understand because of the method name.

In those override methods, you can write java code to save related node name and node text value.

You can also create error handler, DTD handler etc for different usage.

2. SAX Parser Java Code Example.

java xml sax parser example java file structure

Based on previous example Android Parse Xml Use XmlPullParser Example, you just need to add below code in your activity onCreate method.

// When click parse xml use sax parser button.
parseXmlUseSaxButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Create a OkHttpClient request builder.
        Request.Builder builder = new Request.Builder();

        // Set xml file url.
        builder  = builder.url(xmlFileUrl);

        // Build http request.
        Request request =;

        // Create a OkHttp3 Call object.
        Call call = okHttpClient.newCall(request);

        // Execute the get xml file request asynchronously in an automate child thread.
        call.enqueue(new Callback() {

            // If http get request fail.
            public void onFailure(Call call, IOException e) {

            // If http get request success.
            public void onResponse(Call call, Response response) throws IOException {
                // If server response success.
                    // Get response return xml string.
                    String resultXml = response.body().string();

                    // Parse the xml string.
                    String xmlParseResult = parseXmlUseSaxParser(resultXml);

                    // Send message to activity main thread Handler to show the xml parsed result.

2.1 Parse Xml Use SAX Parser Methods.

/* Parse xml string use sax parser.Return parsed string. */
private String parseXmlUseSaxParser(String xmlString)
    StringBuffer retBuf = new StringBuffer();

    try {
        // Create xml sax parser factory.
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();

        // Create sax parser by factory.
        SAXParser saxParser = parserFactory.newSAXParser();

        // Get xml reader object from sax parser.
        XMLReader xmlReader = saxParser.getXMLReader();

        // Create xml content sax handler.
        SaxParserHandler xmlDataHandler = new SaxParserHandler();

        // Set sax parser handler to xml reader.

        // Create a new StringReader.
        StringReader xmlStringReader = new StringReader(xmlString);

        // Get input source from string reader.
        InputSource inputSource = new InputSource(xmlStringReader);

        // Parse xml use sax parser.

        // Get parsed out user info dto list after sax parse.
        List<UserInfoDTO> userInfoDtoList = xmlDataHandler.getUserInfoDTOList();

        // Loop the list, build formatted string to return.
        for(UserInfoDTO userInfoDto : userInfoDtoList)
            retBuf.append("user = " + userInfoDto.getUser() + "\r\n\r\n");
            retBuf.append("email = " + userInfoDto.getEmail() + "\r\n\r\n");
            retBuf.append("title = " + userInfoDto.getTitle() + "\r\n\r\n");
    }catch(Exception ex)
        // Add error message.
    }finally {
        return retBuf.toString();

2.2 Custom SAX Parser Content Handler.

This is the custom content handler which process xml element parsing and get related node name and text value. It’s userInfoDTOList variable is used to save parsed out user info data list.

READ :   Android Thread Message Looper Handler Example

package com.dev2qa.example.xml;

import com.dev2qa.example.xml.dto.UserInfoDTO;

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

import java.util.ArrayList;
import java.util.List;

 * Created by Jerry on 3/5/2018.

public class SaxParserHandler extends DefaultHandler {

    // Used to store parsed out UserInfoDTO list.
    private List<UserInfoDTO> userInfoDTOList = null;

    // Record current parse xml element node name.
    private String currNodeName = "";

    // Save current parsed out UserInfoDTO.
    private UserInfoDTO currUserInfoDto = null;

    public List<UserInfoDTO> getUserInfoDTOList() {
        if(userInfoDTOList == null)
            userInfoDTOList = new ArrayList<UserInfoDTO>();
        return userInfoDTOList;

    public void setUserInfoDTOList(List<UserInfoDTO> userInfoDTOList) {
        this.userInfoDTOList = userInfoDTOList;

    // This method is invoked when start parse xml element node use sax parser.
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // Record current paring xml element node name.
        currNodeName = localName;

    // When sax parse xml element node finished, invoke this method.
    public void endElement(String uri, String localName, String qName) throws SAXException {
        // If this is the end of employee xml element.
            // Add current user info dto to userInfoDto list.
            // Set current user info dto to null.
            currUserInfoDto = null;

    // This method is invoked when sax parser parse xml node text.
    public void characters(char[] ch, int start, int length) throws SAXException {
        // First get the text value.
        StringBuffer strBuf = new StringBuffer();
        if(length > 0) {
            strBuf.append(ch, start, length);

        // Remove node text beginning and ending white space characters ( \r\n etc. ).
        String nodeText = strBuf.toString().trim();

            // If current node is employee then create a new UserInfoDTO instance.
            currUserInfoDto = new UserInfoDTO();
        }else if("user".equalsIgnoreCase(currNodeName))
            if(nodeText.length() > 0) {
                // Set user data.
        }else if("email".equalsIgnoreCase(currNodeName))
            if(nodeText.length() > 0) {
                // Set email data.
        }else if("title".equalsIgnoreCase(currNodeName))
            if(nodeText.length() > 0) {
                // Set title data.

2.3 User Info DTO.

This DTO is used to save parsed out user info.

READ :   Android Implement And Recognize Custom Gesture Example

package com.dev2qa.example.xml.dto;


 * Created by Jerry on 3/5/2018.

public class UserInfoDTO implements Serializable {

    private String user = "";

    private String email = "";

    private String title = "";

    public String getUser() {
        return user;

    public void setUser(String user) {
        this.user = user;

    public String getEmail() {
        return email;

    public void setEmail(String email) { = email;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

Leave a Reply

Your email address will not be published. Required fields are marked *

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