FAQ

What Is The Use Of XML Parsing In Android?

What Is XML Parsing In Android?

What Is Parsing Error On Android?

Refer A Friend

Have a friend to whom you would want to share this course? Refer now and earn credits

Refer Now !
Advanced Android Course Course Topics keyboard_arrow_down

Description

Example for XML in Android

 

In this video we are going to see an example for XML in Android.

First of all we will create one XmlPullParser.

We will need one XML file which we will store in our 'assets' folder to parse.

We will now design the layout of our app by going to activity_main.xml file. Inside which we have taken one ListView.

Now we will see the main code of our application in Employee.java file.

public class Employee

{

private int id;

ptivate string name;

provate 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;

}

Now we will create another class XmlPullParserHandler.java in which we need to parse the XML code.

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();

Now inside our MainActivity.java file, we will add following code,

List<Employee>employees=null;

try

{

XmlPullParserHandler parser = new XmlPullParserHandler();

InputStream is=getAssets().open("employees");

employees=parser.pass(is);

Now we will run code and as we execute the code, the XML file is displayed in front of our screen. Code is running successfully.

Student Testimonials
Download The App
  • Learn anywhere on the go
  • Share content with your friends
  • Evaluate your progress through practice tests
  • No internet connection needed.