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.