Tuesday, 1 December 2015

example for parsing mechanism using xml pull parser in android

Step 1> write the below code where you want to get the result.

ArrayList<Pojo_Name>()  listFromWeb=new ArrayList<Pojo_Name>();
listFromWeb.clear();
InputStream isr=IOUtils.toInputStream(result2);
listFromWeb=SAX_Parser.GetMedicationLog(isr);

NOte : Here result2 is the output response from server.


///////////////////////

Step 2> Create Sample POJO(Plain old java object) class  with the Name of Pojo_Name.java


public class Pojo_Name
{

private String ChildTag1, ChildTag2, ChildTag3;

public String getChildTag1() {
return ChildTag1;
}
public void setChildTag1(String ChildTag1) {
this.ChildTag1= ChildTag1;
}
public String getChildTag2() {
return ChildTag2;
}
public void setChildTag2(String ChildTag2) {
this.ChildTag2= ChildTag2;
}
public String getChildTag3() {
return ChildTag3;
}
public void setChildTag3(String ChildTag3) {
this.ChildTag3= ChildTag3;
}
}







//////////////////////
Step3 > Craeate a .java class with the name of SAX_Parser.java and Write the below code in SAX_Parser.java


public class SAX_Parser {


public static ArrayList<Pojo_Name> GetMedicationLog(InputStream  isr)
{
final ArrayList<Pojo_Name> list=new ArrayList<Pojo_Name>();
try
{
list.clear();
XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
XmlPullParser parser=factory.newPullParser();
parser.setInput(isr, null);
int i=parser.next();
boolean tag_value=false;
Pojo_Name pojo = null;
String value="";

while(i!=parser.END_DOCUMENT)
{
if(i==parser.START_TAG)
{
if(parser.getName().equalsIgnoreCase("MainTag"))
{
tag_value=true;
pojo=new Pojo_Name();
}
            }
if(i==parser.TEXT)
{
if(tag_value)
{
value=parser.getText();
}
}
if(i==parser.END_TAG)
{
if(tag_value)
{
                   if(parser.getName().equalsIgnoreCase("ChildTag1"))
                   {
pojo.setChildTag1(value);
}
  if(parser.getName().equalsIgnoreCase(""ChildTag2"))
                 {
pojo.setChildTag2(value);
                }
                 if(parser.getName().equalsIgnoreCase(""ChildTag3"))
                {
pojo.setChildTag3(value);
                }
}
if(parser.getName().equalsIgnoreCase("MainTag"))
{
tag_value=false;
list.add(pojo);
}
        }//close END_TAG

i=parser.next();
} //Closing of While loop

}
    catch (Exception e)
{
e.printStackTrace();
}
 
     return list;
}
}

No comments:

Post a Comment