XML Parsing - Android Example

DOWNLOAD CODE

Related Examples

In this example we will learn how to parse xml in android. 

For better understanding taking a simple and static xml to parse.

 

Project Structure :

 

xml_Parsing_project_sketch

 


           //Static XML data which we will parse
           final String XMLData = "
                                  <?xml version="1.0"?>
                                    <login>
                                       <status>OK</status>
                                       <jobs>
                                         <job>
                                             <id>4</id>
                                             <companyid>4</companyid>
                                             <company>Android Example</company>
                                             <address>Parse XML Android</address>
                                             <city>Tokio</city>
                                             <state>Xml Parsing Tutorial</state>
                                             <zipcode>601301</zipcode>
                                             <country>Japan</country>
                                             <telephone>9287893558</telephone>
                                             <fax>1234567890</fax>
                                             <date>2012-03-15 12:00:00</date>
                                          </job>
                                          <job>
                                             <id>5</id>
                                             <companyid>6</companyid>
                                             <company>Xml Parsing In Java</company>
                                             <address>B-22</address>
                                             <city>Cantabill</city>
                                             <state>XML Parsing Basics</state>
                                             <zipcode>201301</zipcode>
                                             <country>America</country>
                                             <telephone>9287893558</telephone>
                                             <fax>1234567890</fax>
                                             <date>2012-05-18 13:00:00</date>
                                           </job>
                                        </jobs>
                                     </login>
                                ";

 

 

PLAN STRUCTURE :

 

           1. Make a Model class to store parsed XML node values.
           2. Create a XML parser class to parse XML node values.
           3. Call XML parser and store parsed node value in Model class.

 

 

NOW CODING :

 XmlValuesModel.java

 


public class XmlValuesModel {

            private  int id;
            private  int companyid;
            private  String company = "";
            private  String date = "";
            private  String address="";
            private  String city="";
            private  String state="";
            private  String zipcode="";
            private  String country="";
            private  String telephone="";
            private  String forms="";
            
            /************* Define Setter Methods *********/
            
            public void setid(int id)
            {
                this.id = id;
            }
            public void setcompanyid(int companyid)
            {
                this.companyid = companyid;
            }
            public void setcompany(String company)
            {
                this.company = company;
            }
            public void setaddress(String address)
            {
                this.address = address;
            }
            public void setcity(String city)
            {
                this.city = city;
            }
            public void setstate(String state)
            {
                this.state = state;
            }
            public void setzipcode(String zipcode)
            {
                this.zipcode = zipcode;
            }
            public void setcountry(String country)
            {
                this.country = country;
            }
            public void settelephone(String telephone)
            {
                this.telephone = telephone;
            }
            public void setdate(String date)
            {
                this.date = date;
            }
            
            
            
            /************* Define Getter Methods *********/
            
            public int getid()
            {
                return id;
            }
            
            public String getdate()
            {
                return date;
            }
            public int getcompanyid()
            {
                return companyid;
            }
            public String getcompany()
            {
                return company;
            }
            public String getaddress()
            {
                return this.address;
            }
            public String getcity()
            {
                return this.city;
            }
            
            public String getstate()
            {
                return this.state;
            }
            
            public String getzipcode()
            {
                return this.zipcode;
            }
            
            public String getcountry()
            {
                return this.country;
            }
            
            public String gettelephone()
            {
                return this.telephone;
            }
            public void setforms(String forms)
            {
                this.forms = forms;
            }
            public String getforms()
            {
                return this.forms;
            }
      } 

 

=============================================================================================

 

XMLParser.java

     Parser class to parse each xml node.

 

 


    // SAX parser to parse job 
        
    public class XMLParser extends DefaultHandler
      {
            
                
                List<XmlValuesModel> list=null;
                
                // string builder acts as a buffer
                StringBuilder builder;
            
                XmlValuesModel jobsValues=null;
                
                
                 // Initialize the arraylist
                 // @throws SAXException
                 
                @Override
                public void startDocument() throws SAXException {
                    
                    /******* Create ArrayList To Store XmlValuesModel object ******/
                    list = new ArrayList<XmlValuesModel>();
                }
            
                
                 // Initialize the temp XmlValuesModel object which will hold the parsed info
                 // and the string builder that will store the read characters
                 // @param uri
                 // @param localName ( Parsed Node name will come in localName  )
                 // @param qName
                 // @param attributes
                 // @throws SAXException
                 
                @Override
                public void startElement(String uri, String localName, String qName,
                        Attributes attributes) throws SAXException {
                    
                    /****  When New XML Node initiating to parse this function called *****/
                    
                    // Create StringBuilder object to store xml node value
                    builder=new StringBuilder();
                    
                    if(localName.equals("login")){
                        
                        //Log.i("parse","====login=====");
                    }
                    else if(localName.equals("status")){
                        
                        // Log.i("parse","====status=====");
                    }
                    else if(localName.equals("jobs")){
                        
                    }
                    else if(localName.equals("job")){
                        
                        // Log.i("parse","----Job start----");
                        /********** Create Model Object  *********/
                        jobsValues = new XmlValuesModel();
                    }
                }
                
                
                
                 // Finished reading the login tag, add it to arraylist
                 // @param uri
                 // @param localName
                 // @param qName
                 // @throws SAXException
                 
                @Override
                public void endElement(String uri, String localName, String qName)
                        throws SAXException {
                   
                    
                    if(localName.equals("job")){
 
                        /** finished reading a job xml node, add it to the arraylist **/
                        list.add( jobsValues );
                        
                    }
                    else  if(localName.equalsIgnoreCase("status")){
                        
                        
                    }
                    else  if(localName.equalsIgnoreCase("id")){  
 
                        jobsValues.setid(Integer.parseInt(builder.toString()));
                    }
                    else if(localName.equalsIgnoreCase("companyid")){
 
                        jobsValues.setcompanyid(Integer.parseInt(builder.toString()));
                    }
                    else if(localName.equalsIgnoreCase("company")){
                        jobsValues.setcompany(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("address")){
                        jobsValues.setaddress(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("city")){
                        jobsValues.setcity(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("state")){
                        jobsValues.setstate(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("zipcode")){
                        jobsValues.setzipcode(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("country")){
                        jobsValues.setcountry(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("telephone")){
                        jobsValues.settelephone(builder.toString());
                    }
                    else if(localName.equalsIgnoreCase("date")){
                        jobsValues.setdate(builder.toString());
                    }
                    
                 // Log.i("parse",localName.toString()+"========="+builder.toString());
                }
            
               
                 // Read the value of each xml NODE
                 // @param ch
                 // @param start
                 // @param length
                 // @throws SAXException
                 
                @Override
                public void characters(char[] ch, int start, int length)
                        throws SAXException {
                        
                    /******  Read the characters and append them to the buffer  ******/
                    String tempString=new String(ch, start, length);
                     builder.append(tempString);
                }
      }

 

 

Explanation :

 

                 startDocument() Method :

                      This function called in very parse begin. so create Arraylist type Model Objest . we will store each Model object in this ArrayList.

                 startElement() Method :

                       Called when new XML node starting to parse.    

                       See In Defined XML Node name job is contained data , thatswhy we are checking for job node and then create new Model inside that check.        

 


           else if(localName.equals("job")){
            
                   //Log.i("parse","----Job start----");
                   /********** Create Model Object  *********/
                   jobsValues = new XmlValuesModel();

            }       

 

                           endElement() Method :

                                  This function will call for each node when parsing reached to close of the node.

                                  See In Defined XML Node name job contained other node values , so parse Other node values inside job node and store parsed values in Model Object, then check for job node end and store Model object to ArrayList ( Previously Defined ).

 

 


               if(localName.equals("job")){
               
                    /************* finished reading a job node, add Model Object it to arraylist ********/
                    list.add(jobsValues);
                
                }

 

===================================================================================================

 

ParseXmlAndroidExample.java

This is the main activity class. For this class i have comment explanation.

 

 



public class ParseXmlAndroidExample extends Activity {

    List<XmlValuesModel> myData = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse_xml_android_example);
        
        final TextView output = (TextView) findViewById(R.id.output);
        final Button bparsexml      = (Button) findViewById(R.id.bparsexml);
        
        //Static XML data which we will parse
        final String XMLData = "
                      <?xml version="1.0"?>
                        <login>
                           <status>OK</status>
                           <jobs>
                             <job>
                                 <id>4</id>
                                 <companyid>4</companyid>
                                 <company>Android Example</company>
                                 <address>Parse XML Android</address>
                                 <city>Tokio</city>
                                 <state>Xml Parsing Tutorial</state>
                                 <zipcode>601301</zipcode>
                                 <country>Japan</country>
                                 <telephone>9287893558</telephone>
                                 <fax>1234567890</fax>
                                 <date>2012-03-15 12:00:00</date>
                              </job>
                              <job>
                                 <id>5</id>
                                 <companyid>6</companyid>
                                 <company>Xml Parsing In Java</company>
                                 <address>B-22</address>
                                 <city>Cantabill</city>
                                 <state>XML Parsing Basics</state>
                                 <zipcode>201301</zipcode>
                                 <country>America</country>
                                 <telephone>9287893558</telephone>
                                 <fax>1234567890</fax>
                                 <date>2012-05-18 13:00:00</date>
                               </job>
                            </jobs>
                         </login>
                    ";
        
        String dataToBeParsed = "Click on button to parse XML.\n\n XML DATA : \n\n"+XMLData;
        output.setText(dataToBeParsed);
        
        /****  Button Click Listener ********/
        bparsexml.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
        
                try{
                    
                    /************** Read XML *************/
                    
                    BufferedReader br=new BufferedReader(new StringReader(XMLData));
                    InputSource is=new InputSource(br);
                    
                    /************  Parse XML **************/

                    XMLParser parser=new XMLParser();
                    SAXParserFactory factory=SAXParserFactory.newInstance();
                    SAXParser sp=factory.newSAXParser();
                    XMLReader reader=sp.getXMLReader();
                    reader.setContentHandler(parser);
                    reader.parse(is);
                    
                    /************* Get Parse data in a ArrayList **********/
                    myData=parser.list;
                    
                    if(myData!=null){
                        
                        String OutputData = "";
                        
                        /*************** Get Data From ArrayList *********/

                        for (XmlValuesModel xmlRowData : myData) {
                          if(xmlRowData!=null)
                          {  
                              
                              
                            int     id        = xmlRowData.getid();
                            int     companyid = xmlRowData.getcompanyid();
                            String  company   = xmlRowData.getcompany();
                            String  address   = xmlRowData.getaddress();
                            String  city      = xmlRowData.getcity();
                            String  state     = xmlRowData.getstate();
                            String  zipcode   = xmlRowData.getzipcode();
                            String  country   = xmlRowData.getcountry();
                            String  telephone = xmlRowData.gettelephone();
                            String  date      = xmlRowData.getdate();
                            
                            
                            OutputData += "Job Node : \n\n "+ company +" | "
                                                           + address    +" | " 
                                                           + city       +" | " 
                                                           + state      +" | " 
                                                           + zipcode    +" | "
                                                           + country    +" | "
                                                           + telephone  +" | "
                                                           + date       +" \n\n "
                                                           
                                                   ;
                            
                          }
                          else
                              Log.e("Jobs", "Jobs value null");
                        }
                        
                        /******** Show Data *************/
                        output.setText(OutputData);
                    }   
                }
                catch(Exception e){Log.e("Jobs", "Exception parse xml :"+e);}
            }
        });  
    }
}


 

===================================================================================================

 

activity_parse_xml_android_example.xml

 


          <LinearLayout 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"
                android:orientation="vertical"
                tools:context=".ParseXmlAndroidExample" >
                
                <Button
                     android:id="@+id/bparsexml" 
                     android:text="Parse Xml Android"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content">
                </Button>
 
                <TextView
                    android:id="@+id/output"
                    android:paddingTop="10px"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:text="" />
            
            </LinearLayout>