Monday 28 July 2014

XML Parsing In Android


Today, we are going to create a XML Parser in Android using java language . This tutorial is 100% working tutorial and it will work smoothly i have include the required xml already in the variable .
I have used a very simple code to parse a xml file and showed its data in table layout

Today while creating an Android Application I came to use XML Parsing and also required to use Table Layout to show its retrieved xml data . So i thought of making an article that shows easy to use method and code to parse the xml data into tabulated format

XML Parsing is very cool thing . We need to parse the xml in various situations . Like i am going to why i have used it . Xml parsing is used in situations when the data is going to be retrieved form web service . When we are using or quering the database or when we are dealing with Web Service like .asmx or WCF then the data returned by these webservices are in XML format so in order to view this data result to user we need to parse that xml according to our needs means which element or which node data we want to show and by using this code we can retrieve the required data and we can show it in view or layout of android to user .  


Steps To Parse XML File 

1. First Create New Instance of Document Builder 
2. Then Create a Document from instance of Document Builder Created in First Step
3. Get document elements
4. Get and parse data Node by Node

DOWNLOAD The Required Code Files For Xml Parsing


The Following Snapshot shows the process of parsing of XML data 

XML Data Parsing Process


package com.example.parserxml; 
import java.io.StringReader; i
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.app.ActionBarActivity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.TableLayout; 
import android.widget.TableRow; 
import android.widget.TextView; 

 public class MainActivity extends ActionBarActivity 

 @Override protected void onCreate(Bundle savedInstanceState) 
{
 super.onCreate(savedInstanceState); 
 setContentView(R.layout.activity_main);
 Button mybtn=(Button)findViewById(R.id.MyButton);
 String filename=" " + " Citibank " + " 100 " + " 1000 " + " "; 

try 
 { 
 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
 InputSource is=new InputSource(); 
 is.setCharacterStream(new StringReader(filename)); 

 Document doc; 
 doc=dBuilder.parse(is); 
 doc.getDocumentElement().normalize(); 
 NodeList nodes = doc.getElementsByTagName("STOCK"); 
 for (int i = 0; i < nodes.getLength(); i++) 

 Node node = nodes.item(i); 
 if (node.getNodeType() == Node.ELEMENT_NODE) 
{
//GETTING ALL ELEMENTS UNDER 'STOCK' IN ELEMENT AS ARRAY
 Element element = (Element) node; 

//GETTING VALUE OF SYMBOL UNDER STOCK ELEMENT THAT IS FILLED IN PREVIOUS STEP
 String val=getValue("symbol",element); 

//GETTING VALUE OF PRICE UNDER STOCK ELEMENT THAT IS FILLED IN PREVIOUS STEP
 String val1=getValue("price",element); 

//GETTING VALUE OF QUANTITY UNDER STOCK ELEMENT THAT IS FILLED IN PREVIOUS STEP
 String val2=getValue("quantity",element); 

//SETTING TEXTVALUE OF BUTTON
 mybtn.setText(val); 

//making instance of Table layout
 TableLayout tab=(TableLayout)findViewById(R.id.tab); 

//making instance of table row this refers to this current context
 TableRow tbr=new TableRow(this); 


//creating three textview for values and setting some properties to look cool
TextView Name=new TextView(this); 
TextView Name1=new TextView(this); 
TextView Name2=new TextView(this); 

Name.setPadding(9,9,9,9); 
Name1.setPadding(9,9,9,9); 
Name2.setPadding(9,9,9,9); 
Name.setText(val);         //setting text values 
Name1.setText(val1); 
Name2.setText(val2); 
tbr.addView(Name); 
tbr.addView(Name1); 
tbr.addView(Name2);
tab.addView(tbr); 
 } 
 } 
 } 
catch (Exception ex) 

 mybtn.setText("Exception occured"); 
 ex.printStackTrace();
 } 
 } 

 private static String getValue(String tag, Element element) 

 NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes(); 
 Node node = (Node) nodes.item(0); 
 return node.getNodeValue(); 
 } 

 @Override public boolean onCreateOptionsMenu(Menu menu) 

 // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); 
 return true; 
 } 

 @Override public boolean onOptionsItemSelected(MenuItem item) 
{
 // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. 
 int id = item.getItemId(); 
 if (id == R.id.action_settings) 

 return true;
 } 
 return super.onOptionsItemSelected(item); 
 } /** * A placeholder fragment containing a simple view. */ 

 public static class PlaceholderFragment extends Fragment 

 public PlaceholderFragment() { } 

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 

 View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; 
 } 
 } 
 } 


EXPLANATION OF JAVA CODE

  • DocumentBuilder :- It is an API that parse the content of given xml document as input to document builder instance and after parsing it returns new DOM Document in which all the elements of xml are parsed according to the Document object model ( DOM )


DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 


  • In below this lines of code we are reading the XML Document using StringReader Class We are using InputSource class instance and reading the xml document and filling inputsource object with that data


 InputSource is=new InputSource(); 
 is.setCharacterStream(new StringReader(filename)); 



  • In below lines of code we are exploring XML Document code and getting the data by tagname and converted it into xml nodes by making instance of NodeList Class . Each Node of XML Document is given to node object of Nodelist and in this code we are giving it by tagname


NodeList nodes = doc.getElementsByTagName("STOCK"); 

  • Then now we are exploring the nodes by nodes.item( i ) so in these as we are exloring it by STOCK tagname so each item of nodes will contains the child node of STOCK Parent Node


 Node node = nodes.item(i); 


XML PARSER XML CODE
<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

   <Button
        android:id="@+id/MyButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="" />

   <TableLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/tab"
       >

   <TableRow
           android:id="@+id/tableRow1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" >
       

   <TextView
               android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Column1"
             />


    <TextView
               android:id="@+id/txt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Column2"
             />


     <TextView
               android:id="@+id/txt3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Column3"
             />
          
       </TableRow>
      
   </TableLayout>
 
   

</LinearLayout>

Share this

0 Comment to "XML Parsing In Android"

Post a Comment