Generally, XML (Extensible Mark-up Language) is one of the commonly used data exchange format to interchange the data between servers.
In android, we have a three types of XML parsers to parse the XML data to get the required information in android applications, those are
- DOM Parser
- SAX Parser
- XMLPullParser
Android DOM Parser
In android, DOM parser will use an object based approach to create and parse the XML files in android applications.
To know more about parsing XML using DOM parser in android, check this Android XML Parsing using DOM Parser.
Now we will see how to use SAX parser in android applications to parse the XML document to get the required informations.
Android SAX Parser
In android, SAX stands for Simple API for XML and SAX is widely used API for XML parsing.
The main advantage of SAX parser over a DOM parser is, we can instruct SAX parser to stop midway through a document without losing the data that is already collected.
Same as DOM parser, the SAX parser also used to perform in-memory operations to parse the XML document but it will consume less memory compared to DOM parser.
Basically, the XML file will contain a following 4 main components.
Component | Description |
---|---|
Prolog | Generally, the XML file will start with a prolog. The first line that contains the information about a file is prolog. |
Events | Genrally, the XML file will contain a many events that includes document start and end, tag start and end, etc. |
Text | It's a simple text in xml tag elements. |
Attributes | Attributes are the additional properties of a tag such as value etc. present within the tag. |
Following is the sample structure of XML file with user details in android applications.
<?xml version="1.0" encoding="utf-8"?>
<users>
<user>
<name>Suresh Dasari</name>
<designation>Team Leader</designation>
<loation>Hyderabad</loation>
</user>
<user>
<name>Rohini Alavala</name>
<designation>Agricultural Officer</designation>
<loation>Guntur</loation>
</user>
</users>
If you observe above xml structure it contains a different type of components such as prolog, events, text and attributes.
Android SAX XML Parsing
The SAX parser will examines an XML file, character by character and translates it into a series of events, such as startElement(), endElement() and characters(). A ContentHandler object will process these events to perform appropriate action and the parse() method will sends the events to content object, to deals with them.
To read and parse the XML data using SAX parser in android, we need to create an instance of SAXParserFactory, SAXParser and DefaultHandler objects in android applications.
Following is the code snippet of reading and parsing the XML data using SAX parser in android applications with SAXParserFactory, SAXParser, DefaultHandler and series of events to get the required information from XML objects.
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
String currentValue = "";
boolean currentElement = false;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if(localName.equals("user")){
user = new HashMap<>();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("name"))
user.put("name", currentValue);
else if (localName.equalsIgnoreCase("designation"))
user.put("designation", currentValue);
else if (localName.equalsIgnoreCase("location"))
user.put("location", currentValue);
else if (localName.equalsIgnoreCase("user"))
userList.add(user);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
};
InputStream istream = getAssets().open("userdetails.xml");
parser.parse(istream,handler);
SAXParser parser = parserFactory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
String currentValue = "";
boolean currentElement = false;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if(localName.equals("user")){
user = new HashMap<>();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("name"))
user.put("name", currentValue);
else if (localName.equalsIgnoreCase("designation"))
user.put("designation", currentValue);
else if (localName.equalsIgnoreCase("location"))
user.put("location", currentValue);
else if (localName.equalsIgnoreCase("user"))
userList.add(user);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
};
InputStream istream = getAssets().open("userdetails.xml");
parser.parse(istream,handler);
If you observe above code snippet, we used SAXParserFactory, SAXParser and DefaultHandler with series of events to get the required information from XML objects.
Now we will see how to parse XML data using SAX parser and bind the parsed XML data to Listview in android application with examples.
Android XML Parsing with SAX Parser Example
Following is the example of parsing the XML data and get the required information from it using SAX parser in android applications.
Create a new android application using android studio and give names as XMLParserExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we are done with creation of application, create an assets folder under /src/main folder and add new resource file (userdetails.xml), for that right click on assets folder à add new Android resource file à Give name as userdetails.xml like as shown below.
Now open userdetails.xml file and write the code like as shown below.
userdetails.xml
<?xml version="1.0" encoding="utf-8"?>
<users>
<user>
<name>Suresh Dasari</name>
<designation>Team Leader</designation>
<loation>Hyderabad</loation>
</user>
<user>
<name>Rohini Alavala</name>
<designation>Agricultural Officer</designation>
<loation>Guntur</loation>
</user>
<user>
<name>Trishika Dasari</name>
<designation>Charted Accountant</designation>
<loation>Guntur</loation>
</user>
</users>
Now open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/user_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp" />
</LinearLayout>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/user_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp" />
</LinearLayout>
After that create an another layout file (list_row.xml) in /res/layout folder to show the data in listview, for that right click on layout folder à add new Layout resource file à Give name as list_row.xml and write the code like as shown below.
list_row.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="17dp" />
<TextView
android:id="@+id/designation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_marginTop="7dp"
android:textColor="#343434"
android:textSize="14dp" />
<TextView
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/designation"
android:layout_alignBottom="@+id/designation"
android:layout_alignParentRight="true"
android:textColor="#343434"
android:textSize="14dp" />
</RelativeLayout>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="17dp" />
<TextView
android:id="@+id/designation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_marginTop="7dp"
android:textColor="#343434"
android:textSize="14dp" />
<TextView
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/designation"
android:layout_alignBottom="@+id/designation"
android:layout_alignParentRight="true"
android:textColor="#343434"
android:textSize="14dp" />
</RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.xmlparserexample path and write the code like as shown below
MainActivity.java
package com.tutlane.xmlparserexample;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAdapter;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
HashMap<String,String> user = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
ListView lv = (ListView) findViewById(R.id.user_list);
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
String currentValue = "";
boolean currentElement = false;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if(localName.equals("user")){
user = new HashMap<>();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("name"))
user.put("name", currentValue);
else if (localName.equalsIgnoreCase("designation"))
user.put("designation", currentValue);
else if (localName.equalsIgnoreCase("location"))
user.put("location", currentValue);
else if (localName.equalsIgnoreCase("user"))
userList.add(user);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
};
InputStream istream = getAssets().open("userdetails.xml");
parser.parse(istream,handler);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
lv.setAdapter(adapter);
}
catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
HashMap<String,String> user = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
ListView lv = (ListView) findViewById(R.id.user_list);
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
String currentValue = "";
boolean currentElement = false;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if(localName.equals("user")){
user = new HashMap<>();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("name"))
user.put("name", currentValue);
else if (localName.equalsIgnoreCase("designation"))
user.put("designation", currentValue);
else if (localName.equalsIgnoreCase("location"))
user.put("location", currentValue);
else if (localName.equalsIgnoreCase("user"))
userList.add(user);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
};
InputStream istream = getAssets().open("userdetails.xml");
parser.parse(istream,handler);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
lv.setAdapter(adapter);
}
catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
If you observe above code, we used SAXParserFactory, SAXParser and DefaultHandler with series of events to get the required information from XML files.
Output of Android XML Parsing with SAX Parser Example
When we run above program in android studio we will get the result like as shown below.
This is how we can parse the XML data using SAX parser in android applications to get the required information.
No comments:
Post a Comment