THIS CONTENT DOWNLOAD SHORTLY

Objective

This lesson explains how to parse XML documents and use their data.

 

You will get Final Output:

sax parsing

In this tutorial i’ll will be parsing the following XML file. You can get this xml file by accessing

Download Link
:

 

Step 1 Create Project

Setting Up the Application: Create new project with internet permission.

 

Step 2 Create Needed Classes

We need following three classes in to project:

  1. The first class is the Main Activity class that should be created when you created the project will be your activity.

  2. The second class is the Handler class for handling the data.

  3. The third class will contain all the getters and setters that we need to set the data and retrieve it.

 

Step 3 Content Handle

The content handler is where we need to handle each of the incoming events from the XML.

public class XMLHandler extends DefaultHandler {
 
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
 
public static XMLGettersSetters getXMLData() {
return data;
}
 
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
 
elementOn = true;
 
if (localName.equals("CATALOG"))
{
data = new XMLGettersSetters();
} else if (localName.equals("CD")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
}
}
 
/**
* This will be called when the tags of the XML end.
**/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
 
elementOn = false;
 
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("title"))
data.setTitle(elementValue);
else if (localName.equalsIgnoreCase("artist"))
data.setArtist(elementValue);
else if (localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
else if (localName.equalsIgnoreCase("company"))
data.setCompany(elementValue);
else if (localName.equalsIgnoreCase("price"))
data.setPrice(elementValue);
else if (localName.equalsIgnoreCase("year"))
data.setYear(elementValue);
}
 
/**
* This is called to get the tags value
**/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
 
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
 
}
 
}

More About DefaultHandler class:

More About startElement() method:

More About endElement() method:

Step 4 Make Getters & Setters

Getters & Setters method are used for retrieving the content which are stored into XML file. 

public class XMLGettersSetters {
 
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> artist = new ArrayList<String>();
private ArrayList<String> country = new ArrayList<String>();
private ArrayList<String> company = new ArrayList<String>();
private ArrayList<String> price = new ArrayList<String>();
private ArrayList<String> year = new ArrayList<String>();
 
public ArrayList<String> getCompany() {
return company;
}
 
public void setCompany(String company) {
this.company.add(company);
Log.i("This is the company:", company);
}
 
public ArrayList<String> getPrice() {
return price;
}
 
public void setPrice(String price) {
this.price.add(price);
Log.i("This is the price:", price);
}
 
public ArrayList<String> getYear() {
return year;
}
 
public void setYear(String year) {
this.year.add(year);
Log.i("This is the year:", year);
}
 
public ArrayList<String> getTitle() {
return title;
}
 
public void setTitle(String title) {
this.title.add(title);
Log.i("This is the title:", title);
}
 
public ArrayList<String> getArtist() {
return artist;
}
 
public void setArtist(String artist) {
this.artist.add(artist);
Log.i("This is the artist:", artist);
}
 
public ArrayList<String> getCountry() {
return country;
}
 
public void setCountry(String country) {
this.country.add(country);
Log.i("This is the country:", country);
}
 
}
 

Step 5 Display Retrieved Data

Finally we need to set all the contents with their proper place. So we set all the retrieved data in our Main Activity class. 

public class SAXParserActivity extends Activity {
 
XMLGettersSetters data;
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
/**
* Get the view of the layout within the main layout, so that we can add TextViews.
**/
View layout = findViewById(R.id.layout);
 
/**  
* Create TextView Arrays to add the retrieved data to.
**/
TextView title[];
TextView artist[];
TextView country[];
TextView company[];
TextView price[];
TextView year[];
 
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
 
URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml"); // URL of the XML
 
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
 
} catch (Exception e) {
System.out.println(e);
}
data = XMLHandler.data;
 
/**
* Makes the TextView length the size of the TextView arrays by getting the size of the
**/
title = new TextView[data.getTitle().size()];
artist = new TextView[data.getArtist().size()];
country = new TextView[data.getCountry().size()];
company = new TextView[data.getCompany().size()];
price = new TextView[data.getPrice().size()];
year = new TextView[data.getYear().size()];
 
/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < data.getTitle().size(); i++) {
 
title[i] = new TextView(this);
title[i].setText("Title = "+data.getTitle().get(i));
 
artist[i] = new TextView(this);
artist[i].setText("Artist = "+data.getArtist().get(i));
 
country[i] = new TextView(this);
country[i].setText("Country = "+data.getCountry().get(i));
 
company[i] = new TextView(this);
company[i].setText("Company = "+data.getCompany().get(i));
 
price[i] = new TextView(this);
price[i].setText("Price = "+data.getPrice().get(i));
 
year[i] = new TextView(this);
year[i].setText("Year = "+data.getYear().get(i));
 
((ViewGroup) layout).addView(title[i]);
((ViewGroup) layout).addView(artist[i]);
((ViewGroup) layout).addView(country[i]);
((ViewGroup) layout).addView(company[i]);
((ViewGroup) layout).addView(price[i]);
((ViewGroup) layout).addView(year[i]);
}
setContentView(layout);
}
}

More About XMLReader class please refer:

I hope you enjoy this tutorial and it would be helpful to you.

Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in India.

An entrepreneur who has founded 2 flourishing software firms in 7 years, Tejas is keen to understand everything about gaming - from the business dynamics to awesome designs to gamer psychology. As the founder-CEO of a company that has released some very successful games, he knows a thing or two about gaming. He shares his knowledge through blogs and talks that he gets invited to.

face mask Belial The Demon Headgear Pocket Staff Magic