Android tutorial - Android xmlpullparser | xmlpullparser - android app development - android studio - android development tutorial



 android xmlparser client details

What is XMLPullParser?

  • Android recommends to use XMLPullParser to parse the xml file than SAX and DOM because it is fast.
  • The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document using XMLPullParser.
  • XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API.
  • There are following different kinds of parser depending on which features are set:
  • non-validating parser as defined in XML 1.0 spec when FEATURE_PROCESS_DOCDECL is set to true
  • validating parser as defined in XML 1.0 spec when FEATURE_VALIDATION is true (and that implies that FEATURE_PROCESS_DOCDECL is true)
  • when FEATURE_PROCESS_DOCDECL is false (this is default and if different value is required necessary must be changed before parsing is started) then parser behaves like XML 1.0 compliant non-validating parser under condition that no DOCDECL is present in XML documents (internal entites can still be defined with defineEntityReplacementText()). This mode of operation is intended for operation in constrained environments such as J2ME.
  • android xml parser sample code
  • There are two key methods: next() and nextToken(). While next() provides access to high level parsing events, nextToken() allows access to lower level tokens.
  • The current event state of the parser can be determined by calling the getEventType() method. Initially, the parser is in the START_DOCUMENT state.
  • The method next() advances the parser to the next event. The int value returned from next determines the current parser state and is identical to the value returned from following calls to getEventType ().

Events of XmlPullParser

  • next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use four constants (works as the event) defined in the XMLPullParser interface.
  • START_TAG :An XML start tag was read.
  • TEXT :Text content was read; the text content can be retrieved using the getText() method.
  • END_TAG : An end tag was read.
  • END_DOCUMENT :No more events are available

Example of android XMLPullParser

activity_main.xml

  • Drag the one listview from the pallete. Now the activity_main.xml file will look like this:
  • File: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
  
    <ListView  
        android:id="@+id/listView1"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content" >  
  
    </ListView>  
  
</RelativeLayout>  
click below button to copy the code from android tutorial team

xml document

  • Create an xml file named employees.xml inside the assets directory of your project.
  • File: employees.xml
<?xml version="1.0" encoding="UTF-8"?>  
<employees>  
    <employee>  
        <id>1</id>  
        <name>Sachin</name>  
        <salary>50000</salary>        
    </employee>  
    <employee>  
        <id>2</id>  
        <name>Nikhil</name>  
        <salary>60000</salary>    
    </employee>  
      
</employees>  
click below button to copy the code from android tutorial team

Employee class

  • Now create the Employee class that corresponds to the xml file.
  • File: Employee.java
package com.example.xmlpullparsing;  
public class Employee {  
     private int id;  
     private String name;  
     private float salary;  
        public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public float getSalary() {  
        return salary;  
    }  
    public void setSalary(float salary) {  
        this.salary = salary;  
    }  
  
    @Override  
    public String toString() {  
        return " Id= "+id + "\n Name= " + name + "\n Salary= " + salary;  
    }  
}  
click below button to copy the code from android tutorial team

XMLPullParserHandler class

  • Now write the code to parse the xml file using XMLPullParser. Here, we are returning all the employee in list.
  • File: XMLPullParserHandler.java
package com.example.xmlpullparsing;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.List;  
import org.xmlpull.v1.XmlPullParser;  
import org.xmlpull.v1.XmlPullParserException;  
import org.xmlpull.v1.XmlPullParserFactory;  
   
  
public class XmlPullParserHandler {  
    private List<Employee> employees= new ArrayList<Employee>();  
    private Employee employee;  
    private String text;  
   
    public List<Employee> getEmployees() {  
        return employees;  
    }  
   
    public List<Employee> parse(InputStream is) {  
           try {  
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
            factory.setNamespaceAware(true);  
            XmlPullParser  parser = factory.newPullParser();  
   
            parser.setInput(is, null);  
   
            int eventType = parser.getEventType();  
            while (eventType != XmlPullParser.END_DOCUMENT) {  
                String tagname = parser.getName();  
                switch (eventType) {  
                case XmlPullParser.START_TAG:  
                    if (tagname.equalsIgnoreCase("employee")) {  
                        // create a new instance of employee  
                        employee = new Employee();  
                    }  
                    break;  
   
                case XmlPullParser.TEXT:  
                    text = parser.getText();  
                    break;  
   
                case XmlPullParser.END_TAG:  
                    if (tagname.equalsIgnoreCase("employee")) {  
                        // add employee object to list  
                        employees.add(employee);  
                    }else if (tagname.equalsIgnoreCase("id")) {  
                        employee.setId(Integer.parseInt(text));  
                    }  else if (tagname.equalsIgnoreCase("name")) {  
                        employee.setName(text);  
                    } else if (tagname.equalsIgnoreCase("salary")) {  
                        employee.setSalary(Float.parseFloat(text));  
                    }   
                    break;  
   
                default:  
                    break;  
                }  
                eventType = parser.next();  
            }  
   
        } catch (XmlPullParserException e) {e.printStackTrace();}   
        catch (IOException e) {e.printStackTrace();}  
   
        return employees;  
    }  
}  
click below button to copy the code from android tutorial team

MainActivity class

  • Now, write the code to display the list data in the ListView.
  • File: MainActivity.java
package com.example.xmlpullparsing;  
  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.List;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
import android.widget.ArrayAdapter;  
import android.widget.ListView;  
  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
       ListView listView = (ListView) findViewById(R.id.listView1);  
          
        List<Employee> employees = null;  
        try {  
            XmlPullParserHandler parser = new XmlPullParserHandler();  
            InputStream is=getAssets().open("employees.xml");  
            employees = parser.parse(is);  
              
            ArrayAdapter<Employee> adapter =new ArrayAdapter<Employee>  
    (this,android.R.layout.simple_list_item_1, employees);  
            listView.setAdapter(adapter);  
              
        } catch (IOException e) {e.printStackTrace();}  
          
    }  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.activity_main, menu);  
        return true;  
    }  
      }  
click below button to copy the code from android tutorial team

Output:

 output of xml parser

Related Searches to Android xmlpullparser | xmlpullparser