Learning to Parse XML Data in Your Android App


Introduction

We are in an age where, typically, an application cannot work in total isolation and does not have all the data it needs to do its work. It generally has to communicate to some other application–maybe over the internet–and read or send some data to it.
However, the applications with which your app communicates might not be developed using the same technology as yours. For smooth data exchanges between your app and some other application you might be exchanging data in an open format like Extensible Markup language or XML.
An XML document is a human readable text document that contains some starting and ending tags with attributes and data in those tags. Most of the languages and platforms have support for parsing and creating XML documents in them. Android also provides us APIs so that we can work and process XML documents in our app with ease and flexibility. In this article, we are going to see how you can work effectively with XML documents in your Android app.

The classes for XML parsing in Android

There are various XML parsers we can use on the Android platform. For XML, Android recommends the use of the XMLPullParser. Android gives a multiple implementation of the XMLPullParser and you can use any of them in your program. Depending on the way you create your XMLPullParser, the implementation of the parser will be chosen.

Instantiating your parser

As stated above, there are multiple ways in Android you can create an XMLPullParser. The first way to do it is using the Xml class as shown below:
xmlpullparser parser = Xml.newPullParser();
You have to just call newPullParser which will return you a reference to the XMLPull parser. Or you can get a reference from the XmlPullParserFactory as shown below.
XmlPullParserFactory pullParserFactory;
  try {
   pullParserFactory = XmlPullParserFactory.newInstance();
   XmlPullParser parser = pullParserFactory.newPullParser();
  } catch (XmlPullParserException e) {

   e.printStackTrace();
  }

Parsing the XML

Once we have the parser reference it’s now time to use it to parse an XML. We are going to use the following XML as the XML to parse. So now create a file called temp.xml in your assets folder with the content:
<?xml version="1.0" encoding="UTF-8"?>
<products>
 <product>     
  <productname>Jeans</productname>
  <productcolor>red</productcolor>
  <productquantity>5</productquantity>
 </product>
 <product>     
  <productname>Tshirt</productname>
  <productcolor>blue</productcolor>
  <productquantity>3</productquantity>
 </product>
 <product>     
  <productname>shorts</productname>
  <productcolor>green</productcolor>
  <productquantity>4</productquantity>
 </product>
</products>
The code of the activity to read and parse is as follows:
class Product
{

 public String name;
 public String quantity;
 public String color;

}
public class XMLDemo extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  XmlPullParserFactory pullParserFactory;
  try {
   pullParserFactory = XmlPullParserFactory.newInstance();
   XmlPullParser parser = pullParserFactory.newPullParser();

       InputStream in_s = getApplicationContext().getAssets().open("temp.xml");
          parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
             parser.setInput(in_s, null);

             parseXML(parser);

  } catch (XmlPullParserException e) {

   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 private void parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
 {
  ArrayList<product> products = null;
        int eventType = parser.getEventType();
        Product currentProduct = null;

        while (eventType != XmlPullParser.END_DOCUMENT){
            String name = null;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                 products = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name == "product"){
                        currentProduct = new Product();
                    } else if (currentProduct != null){
                        if (name == "productname"){
                            currentProduct.name = parser.nextText();
                        } else if (name == "productcolor"){
                         currentProduct.color = parser.nextText();
                        } else if (name == "productquantity"){
                            currentProduct.quantity= parser.nextText();
                        }  
                    }
                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("product") && currentProduct != null){
                     products.add(currentProduct);
                    } 
            }
            eventType = parser.next();
        }

        printProducts(products);
 }

 private void printProducts(ArrayList</product><product> products)
 {
  String content = "";
  Iterator</product><product> it = products.iterator();
  while(it.hasNext())
  {
   Product currProduct  = it.next();
   content = content + "nnnProduct :" +  currProduct.name + "n";
   content = content + "Quantity :" +  currProduct.quantity + "n";
   content = content + "Color :" +  currProduct.color + "n";

  }

  TextView display = (TextView)findViewById(R.id.info);
  display.setText(content);
 }

 @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;
 }

}
In the above code we have created a small class called Product which has three members: name, quantity and color.
In the activity we first get the XMLPullParser instance then we open the temp.xml as an inputstream. Once that is done we set the inputstream as input to the parser. Then we parse the xml in our functionparseXML.
In the function parseXML we create an ArrayList in which we will store all the products which we will parse from the XML. Once that is done we create a loop which will work till the end of the document is reached.
At the start of the document we created the ArrayList of products. If a tag starts and if the tag is product we know that now it’s a new product so we create a new product instance. Then if the other tags are read we will just read and add the values in our Product instance.
Once the Product tag is ended we add the product to the ArrayList. Once all the products are added we call the function printProducts in which we iterate over the ArrayList and then print the values on the screen.
If we run the activity now we will see the output as follows:
Android XMLDemo display

Other Parsers used for XML

DOM

There are other parsers also that can be used to parse XML in Android. The DOM parser can be used which creates a complete memory model of the XML and can be used to either create or parse XML. DOM parsers generally consume a lot of memory.
You can get the instance of a DOMBuilder as shown below
  try {
   DocumentBuilderFactory DOMfactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder DOMbuilder = DOMfactory.newDocumentBuilder();

  } catch (ParserConfigurationException e) {

   e.printStackTrace();
  }

SAX Parsers

The SAXParsers can also be used to parse XML and consume much lesser memory then DOM parsers. TheSAXParsers can be used only to parse XMLs not to create them. You can get the reference of aSAXParser as shown below:
SAXParserFactory SAXfactory = SAXParserFactory.newInstance();
        try {
            SAXParser SAXParserObj = SAXfactory.newSAXParser();

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

Conclusion

XML documents are becoming a standard way to exchange data between applications over the internet. With our Android apps becoming smarter and smarter it might be necessary for your Android app to communicate and exchange data between different applications over the internet. Android provides a rich set of APIs to work with XML documents in your Android app.
With the help of these APIs you can easily incorporate XML into your Android app. The XML parsers do the tedious work of parsing the XML and we have to just write the code to fetch the appropriate information from it and store it for further processing.
So, have fun processing XML in your next Android app.

0 comments :