Friday, February 26, 2010

Sample SAXParser in Android

In this aritcle discuss about  “How to properly parse XML  using a SAXParser”. 

1.Create  a Customized Handler based on the XML
2.Create a ParserHelper Class
3.Implement the parser and get the Data.

Create  a Customized Handler based on the XML
You can create customized handler using the DefaultHandler class for your xml.

Step : 1 [Create a Handler which extends DefaultHandler]
    class MyDefaultHandler extends DefaultHandler {
    }
   



Step : 2 [ Override the Methods and implement the Code]       
   
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        _tmpValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equalsIgnoreCase("uname")) {
            _tmpKey = _tmpValue;
        } else if (localName.equalsIgnoreCase("pwd")) {
            userList.put(_tmpKey.trim(), _tmpValue);
        }
    }


Create a ParserHelper Class
Create an instance for customized handler class
    MyDefaultHandler df = new MyDefaultHandler();   

Create an instance for SAXParserFactory,SAXParser and XMLReader
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();


Set the content Handler
    xr.setContentHandler(df);

Set the XML Content   
Type 1:
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(parseContent));


Type 2:
    URL url = new     URL("http://www.DOMAON.com/File.xmll");
   
   
Parser the XML
    xr.parse(is); [For type1]
    xr.parse(new InputSource(url.openStream())); [For type2]


Implement the parser and get the Data

Create an instance for helper class and call the parserContent method
  
    SAXHelper sh = new SAXHelper();
    sh.parseContent(content);
             

Sample Source

MyDefaultHandler.java


class MyDefaultHandler extends DefaultHandler {

    String _tmpValue = "", _tmpKey = "";
    public HashMap<String, String> userList = new HashMap<String, String>();

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        _tmpValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equalsIgnoreCase("uname")) {
            _tmpKey = _tmpValue;
        } else if (localName.equalsIgnoreCase("pwd")) {
            userList.put(_tmpKey.trim(), _tmpValue);
        }
    }
}


SAXHelper.java
public class SAXHelper {   
    public HashMap<String, String> userList = new HashMap<String, String>();
    public void parseContent(String parseContent) {
        MyDefaultHandler df = new MyDefaultHandler();
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();           
            xr.setContentHandler(df);
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(parseContent));           
            xr.parse(is);           
            userList = df.userList;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Implementation Class

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        String content = "<root><uname>ganesan</uname><pwd>pwd2</pwd> <uname>rama</uname><pwd>pwd1</pwd> </root>";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.TextView01);
        SAXHelper sh = new SAXHelper();
        sh.parseContent(content);
        String data = (String) sh.userList.get("ganesan");
        Log.d("DATA", data);
        tv.setText(data);

    }
  


6 comments:

  1. There are better parser than SAX, like pull parser or vtd-xml... they can significantly simplify coding

    http://vtd-xml.sf.net

    ReplyDelete
  2. Yes,

    But vtd-xml.jar is 450K in size, adding significantly to the weight of an android app, so why do this when you have a native parser?

    ReplyDelete
  3. i am not getting properly any of the parsers

    ReplyDelete
  4. Thanks for this article on how to properly parse XML using a SAXParser. I found it helpful. I compiled a list of some top resources on building an android sax parser; I included your post. Check it out, feel free to share. Hope other developers find this useful too. http://www.verious.com/board/Giancarlo-Leonio/building-an-android-sax-parser

    ReplyDelete
  5. Excellent content ,Thanks for sharing this .,
    Leanpitch provides online training in ICP ACC, everyone can use it wisely.
    Certified Agile coach certification
    Agile coach

    ReplyDelete