How to parse XML using SAX parser in Android?


Introduction

Android is an open-source operating system which is based on the linux kernel which is developed by Google. There are several ways which we can use to parse the data within our android application such as JSON parsing, xml parsing and many more. For parsing of the XML file SAX parser is used. In this article we will take a look at How to parse XML using SAX parser in Android.

Implementation

We will be creating a simple application in which we will be creating a text view for displaying the heading of our application. After that we are creating one more text view in which we will be displaying the data parsed from an xml file using SAX parser. Now let's move towards android studio for creating a new project in Android Studio.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note : Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <!-- on below line creating the heading of our application -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@id/idTVParser"
       android:layout_margin="10dp"
       android:layout_marginTop="90dp"
       android:padding="8dp"
       android:text="XML Parsing in Android using SAX Parser"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!-- on below line creating a list view for displaying the list of programming languages -->
   <TextView
       android:id="@+id/idTVParser"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_margin="8dp"
       android:padding="4dp"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
</RelativeLayout>

Explanation − In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating one more text view in which we will be displaying the data which is being parsed from the xml file.

Step 3 : Creating an XML file for storing our data

Navigate to app>java>your app’s package name>Right click on it>New Folder>Assets Folder. Now the assets folder will be created. Now we will be creating an xml file inside our assets folder. For creating an xml file. Navigate to assets folder Right click on it>New Android resource file and name it as file.xml. After creating that file add below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<records>
   <!-- on below line creating a language and inside that creating a name and description for it -->
   <language>
       <name>Java</name>
       <description>Java is a high-level, class-based, object-oriented programming language that is
           designed to have as few implementation dependencies as possible.
       </description>
   </language>
</records>

Step 4 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class MainActivity extends AppCompatActivity {
   // creating variable for text view on below line.
   private TextView parserTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables for text view on below line.
       parserTV = findViewById(R.id.idTVParser);
       try {
           // creating a variable for sax parser factory on below line.
           SAXParserFactory factory = SAXParserFactory.newInstance();
           // creating and initializing variable for sax parser on below line.
           SAXParser saxParser = factory.newSAXParser();
           // creating a variable for default handler and initializing it on below line.
           DefaultHandler handler = new DefaultHandler() {
               // creating a boolean for language name..
               boolean name = false;
               // creating a boolean variable for kanguage description.
               boolean description = false;

               // on below line creating a method to check start element.
               public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                   // on below line checking if name is present in the xml and of present marking the name boolean variable as true.
                   if (qName.equalsIgnoreCase("name")) {
                       name = true;
                   }
                   // on below line checking if description for the language is present in the xml and then marking the description also as true.
                   if (qName.equalsIgnoreCase("description")) {
                       description = true;
                   }
               }

               // on below line creating an end element method.
               public void endElement(String uri, String localName, String qName) throws SAXException {
               }

               // on below line getting characters from the method.
               public void characters(char ch[], int start, int length) throws SAXException {
                   // on below line checking if name is true
                   if (name) {
                       // on below line setting name in our parse text view.
                       // changing the name to false.
                       parserTV.setText(parserTV.getText() + new String(ch, start, length) + "

"); name = false; } // on below line checking if description is true. if (description) { // on below line setting description in our parse text view. // changing the description to false. parserTV.setText("

" + parserTV.getText() + new String(ch, start, length)); description = false; } }//end of characters };//end of DefaultHandler object // on below line getting thr file using input stream. InputStream is = getAssets().open("file.xml"); // on below line parsing the file using sax parser saxParser.parse(is, handler); // on below line handling the exception. } catch (Exception e) { e.printStackTrace(); } } }

Explanation − In the above code firstly we are creating variables for our text view. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the text view variable with the id which we have given in our activity_main.xml file. After that we are creating and initializing variables for SAX Parser Factory, SAX Parser and Default handler in a try catch block.

Inside this we are creating a start element and end element method. The start element method will check whether the data which we are searching is present in the xml. Then we are creating a characters method which is used to read the data from the xml file and set that data to our text view. After that we are creating an input stream and passing the file name for which we have to load data. In our case we are passing the file name as file.xml. Then we are calling the sax parser parse method to parse the data. Lastly we are adding a catch block for exception handling.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note : Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above article we have taken a look at How to parse XML using the SAX parser in Android.

Updated on: 09-May-2023

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements