XML Parser in android

XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it.

Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficient and easy to use. So we are going to use XMLPullParser for parsing XML.

The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only.

<?xml version="1.0"?>
<current>
   
   <city id="2643743" name="London">
      <coord lon="-0.12574" lat="51.50853"/>
      <country>GB</country>
      <sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
   </city>
   
   <temperature value="289.54" min="289.15" max="290.15" unit="kelvin"/>
   <humidity value="77" unit="%"/>
   <pressure value="1025" unit="hPa"/>
</current>


XML - Parsing

In the next step, we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −

private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();

The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −

myparser.setInput(stream, null);

The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −

int event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)  {
   String name=myParser.getName();
   switch (event){
      case XmlPullParser.START_TAG:
      break;
      
      case XmlPullParser.END_TAG:
      if(name.equals("temperature")){
         temperature = myParser.getAttributeValue(null,"value");
      }
      break;
   }		 
   event = myParser.next(); 					
}

The method getEventType returns the type of event that happens. e.g: Document start , tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature , so we just check in conditional statement that if we got a temperature tag , we call the method getAttributeValue to return us the value of temperature tag.