XML Parsing Using SAX Parser

Android provides the facility to parse the xml file using different parsers such as SAX, DOM, etc. The SAX parser cannot be used to create the XML file, It can be used to parse the XML file only.

Parsing is an important part in any development cycle and so it is very important in android as well. Storing data on android device is not good and safe when you have a large amount of data. So we store the data on server and return it in XML format, then we parse it and show it on android device.

If you see SAX parser on wikipedia you will find below definition for it

“SAX (Simple API for XML) is an event-driven online algorithm for parsing XML documents, with an API interface developed by the XML-DEV mailing list. SAX provides a mechanism for reading data from an XML document that is an alternative to that provided by the Document Object Model (DOM).”

To parse the data using SAX you can create an InputStream either from a URL or from local file. In this tutorial we will store an xml file into assets and make an InputStream and parse it. Follow the steps below as given:

Step1: Create a new android project with name SAXxmlParsing.

Step2: Create an XML file named exampleXML.xml inside the assets directory and write the following into it:




Step3: Create a Textview in your main.xml as below to display the data fetched from xml:




Step4: Write the following into your MainActivity.java:




And the output will display the list of hotels with address parsed from the xml file. as below:


You can store example XML file on server as well instead of assets folder. If you do so, you will need URL of the file to create InputStream object.

Check my post on Android XML Resources to read more on XML Pull Parser.

Leave a Comment: