android-studio
  1. android-studio-xml-parsing-sax

Android Studio XML Parsing SAX

Syntax

SAX (Simple API for XML) is an event-based parsing model, which means it parses the XML document from top to bottom and triggers events when it encounters elements, attributes, and values. The syntax for working with SAX is as follows:

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

public class MyHandler extends DefaultHandler {

    // override startElement, endElement, characters methods

}

// create XMLReader instance
XMLReader reader = XMLReaderFactory.createXMLReader();

// create an instance of your handler class
MyHandler handler = new MyHandler();

// set your handler as the content handler for the reader
reader.setContentHandler(handler);

// parse the XML document
reader.parse(new InputSource(new StringReader(xml)));

Example

Let's consider an example of parsing an XML file that contains information about different books. The XML file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Android App Development</title>
        <author>John Doe</author>
        <isbn>1234567890</isbn>
    </book>
    <book>
        <title>iOS App Development</title>
        <author>Jane Doe</author>
        <isbn>0987654321</isbn>
    </book>
</library>

To parse this XML file using SAX, we can create a "Book" class with attributes for the different elements:

public class Book {
    private String title;
    private String author;
    private String isbn;
    // getters and setters
}

We can then create a custom SAX handler class that will be used to parse the XML file and populate a list of books:

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

public class BookHandler extends DefaultHandler {
    private List<Book> books = new ArrayList<>();
    private boolean inTitle = false;
    private boolean inAuthor = false;
    private boolean inIsbn = false;
    private String currentTitle;
    private String currentAuthor;
    private String currentIsbn;

    public List<Book> getBooks() {
        return books;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("book")) {
            currentTitle = "";
            currentAuthor = "";
            currentIsbn = "";
        } else if (qName.equalsIgnoreCase("title")) {
            inTitle = true;
        } else if (qName.equalsIgnoreCase("author")) {
            inAuthor = true;
        } else if (qName.equalsIgnoreCase("isbn")) {
            inIsbn = true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("book")) {
            books.add(new Book(currentTitle, currentAuthor, currentIsbn));
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (inTitle) {
            currentTitle = new String(ch, start, length);
            inTitle = false;
        } else if (inAuthor) {
            currentAuthor = new String(ch, start, length);
            inAuthor = false;
        } else if (inIsbn) {
            currentIsbn = new String(ch, start, length);
            inIsbn = false;
        }
    }
}

Finally, we can use this handler to parse the XML file and populate a list of books:

String xml = "insert your XML string here";
BookHandler handler = new BookHandler();
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
List<Book> books = handler.getBooks();

Output

The output of the example above will be a list of books:

[
    {
        "title": "Android App Development",
        "author": "John Doe",
        "isbn": "1234567890"
    },
    {
        "title": "iOS App Development",
        "author": "Jane Doe",
        "isbn": "0987654321"
    }
]

Explanation

SAX parsing involves three main components: the XML document, the parser, and the handler.

The parser is responsible for reading and interpreting the XML document, and the handler is responsible for generating events based on the elements, attributes, and values encountered in the document.

As the parser reads through the document, it generates events like "start element", "end element", and "characters". These events are then passed to the handler, which can perform custom actions based on the events received.

For example, in the handler class used in the example above, the code in the startElement method checks which element is being encountered and sets a boolean flag to indicate which element is currently being read. The code in the characters method then reads the text content of the current element, and the code in the endElement method constructs a book object and adds it to the list of books whenever the end of a book element is encountered.

Use

SAX parsing is useful for parsing large XML documents, as it only needs to read and process parts of the document as they are encountered. This makes it much more memory-efficient than document object model (DOM) parsing, which reads the entire document into memory before processing it.

SAX parsing is also useful when the XML document is being streamed, rather than being read from a file or retrieved from a server. In this case, the parser can read the document in real-time and trigger events as data becomes available.

Important Points

  • SAX is an event-based parsing model.
  • SAX parses the XML document from top to bottom and triggers events when it encounters elements, attributes, and values.
  • SAX parsing is more memory-efficient than DOM parsing for large XML documents.
  • SAX parsing is useful for processing streamed XML data.

Summary

SAX parsing is a powerful and efficient way to parse XML documents in Android Studio. By using a custom SAX handler class, you can parse specific elements and attributes from the document and process them as needed. This makes SAX parsing an ideal tool for working with large or streamed XML data in Android applications.

Published on: