Harish
Harish

Reputation: 3117

How to get data using SAX parsing in android

Can any body show how to get the data from xml document using SAX parsing for below XML example.

<root>
   <parent>
      <child1>xyz</child1>
      <child2>abc</child2>
   </parent>
</root>        

for this how can we write the sax parsing code in android.

Thanks for helping...

Upvotes: 1

Views: 832

Answers (2)

Amit Prajapati
Amit Prajapati

Reputation: 14315

    public class JaappApplication extends Application {
        public static final int FAIL = 0;
        public static final int SUCCESS = 1;

        //XML parsers
        public static final int QUESTIONS = 0;


        //PUTEXTRAS 
        public static final String SUBJECTID = "subjectid";
        public static String subtypeid;
        public static String subtypeoption;

    }

    public static ArrayList<QuestionsDto> getQuestionsDtos(String quesid)
    {
        ArrayList<QuestionsDto> arr = new ArrayList<QuestionsDto>();
        String url1 = url + "getquestions.php?subjectid=" + quesid;
        XMLParser xmlParser = new XMLParser(JaappApplication.QUESTIONS);
        int x = xmlParser.parseXml(url1, JaappApplication.QUESTIONS);
        arr = xmlParser.getQuestions();
        return arr;
    }

                package com.jaapp.xmlparsing;

        import java.io.InputStream;
        import java.net.URI;
        import java.net.UnknownHostException;
        import java.util.ArrayList;

        import javax.xml.parsers.SAXParser;
        import javax.xml.parsers.SAXParserFactory;

        import org.apache.http.HttpResponse;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.xml.sax.InputSource;
        import org.xml.sax.XMLReader;

        import com.jaapp.application.JaappApplication;
        import com.jaapp.dto.QuestionsDto;

        import android.util.Log;

        public class XMLParser {
            protected static final String TAG = XMLParser.class.getCanonicalName();
            private static QuestionsReader questionHandler;

            public XMLParser(int initHandler) {
                if (initHandler == JaappApplication.QUESTIONS) {
                    questionHandler = new QuestionsReader();
                }
            }

            public int parseXml(String parseString, int type) {
                try {
                    /* Create a URL we want to load some xml-data from. */
                    URI lUri = new URI(parseString);

                    // Prepares the request.
                    HttpClient lHttpClient = new DefaultHttpClient();
                    HttpGet lHttpGet = new HttpGet();
                    lHttpGet.setURI(lUri);

                    // Sends the request and read the response
                    HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
                    InputStream lInputStream = lHttpResponse.getEntity().getContent();
                    int status = lHttpResponse.getStatusLine().getStatusCode();

                    /* Get a SAXParser from the SAXPArserFactory. */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    spf.setNamespaceAware(true);
                    SAXParser sp = spf.newSAXParser();

                    /* Get the XMLReader of the SAXParser we created. */
                    XMLReader xr = sp.getXMLReader();
                    if(type == JaappApplication.QUESTIONS)  {
                        xr.setContentHandler(questionHandler);  
                    }


                    /* Create a new ContentHandler and apply it to the XML-Reader */

                    /* Parse the xml-data from our URL. */

                    if (!((status >= 200) && (status < 300))) {
                    }
                    else
                    {
                        InputSource is = new InputSource(lInputStream);
                        is.setEncoding("ISO-8859-1");
                        xr.parse(is);

                    }
                    /* Parsing has finished. */
                    return JaappApplication.SUCCESS;
                }
                catch(UnknownHostException e)
                {
                    Log.e(TAG, e.toString());
                    return JaappApplication.FAIL;
                }
                catch (Exception e) {
                    /* Display any Error to the GUI:. */
                    Log.e(TAG, e.toString());
                    return JaappApplication.FAIL;
                }

            }

            public int parseXml(InputStream is, int type) {
                try {
                    /* Get a SAXParser from the SAXPArserFactory. */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    spf.setNamespaceAware(true);
                    SAXParser sp = spf.newSAXParser();

                    /* Get the XMLReader of the SAXParser we created. */
                    XMLReader xr = sp.getXMLReader();
                    if(type == JaappApplication.QUESTIONS)  {
                        xr.setContentHandler(questionHandler);  
                //  }   else if(type == NRTApplication.BOTTOMAD)    {
                //      xr.setContentHandler(myBottomAdHandler);    
                    }

                    /* Create a new ContentHandler and apply it to the XML-Reader */

                    /* Parse the xml-data from our URL. */
                    InputSource is1 = new InputSource(is);
                    is1.setEncoding("ISO-8859-1");
                    xr.parse(is1);
                    /* Parsing has finished. */
                    return JaappApplication.SUCCESS;
                }
                catch(UnknownHostException e)
                {
                    Log.e(TAG, e.toString());
                    return JaappApplication.FAIL;
                }
                catch (Exception e) {
                    /* Display any Error to the GUI:. */
                    Log.e(TAG, "Exception XML parser: " + e.toString());
                    return JaappApplication.FAIL;
                }

            }


            public ArrayList<QuestionsDto> getQuestions() {
                return questionHandler.getQuestions();
            }



        }












        package com.jaapp.xmlparsing;

        import java.util.ArrayList;

        import org.xml.sax.Attributes;
        import org.xml.sax.SAXException;
        import org.xml.sax.helpers.DefaultHandler;

        import android.util.Log;

        import com.jaapp.dto.QuestionsDto;

        public class QuestionsReader extends DefaultHandler {
            private static final String TAG = QuestionsReader.class.getCanonicalName();
            private String tempVal;
            private ArrayList<QuestionsDto> completeQuestionsList;
            private QuestionsDto tempQues;

            public QuestionsReader() {
                completeQuestionsList = new ArrayList<QuestionsDto>();
            }

            @Override
            public void startDocument() throws SAXException {
            }

            @Override
            public void endDocument() throws SAXException {
                // Nothing to do
            }

            @Override
            public void startElement(String uri, String localName, String qName,
                    Attributes attributes) throws SAXException {
                if (localName.equalsIgnoreCase("question")) {
                    tempQues = new QuestionsDto();
                }
                tempVal = "";
            }

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

            @Override
            public void endElement(String uri, String localName, String qName)
                    throws SAXException {
                if (localName.equalsIgnoreCase("question")) {
                    completeQuestionsList.add(tempQues);
                } else if(localName.equalsIgnoreCase("id")) {
                    tempQues.setQid(tempVal);
                } else if(localName.equalsIgnoreCase("level")) {
                    tempQues.setQlevel(Integer.parseInt(tempVal));
                } else if(localName.equalsIgnoreCase("description")) {
                    tempQues.setQquestion(tempVal);
                }
            }

            public ArrayList<QuestionsDto> getQuestions() {
                return completeQuestionsList;
            }
        }

Upvotes: 1

Lalit Poptani
Lalit Poptani

Reputation: 67286

There are lots of SAX Tutorial and answers available. Here is one of the good answers on StackOverflow that explains a clean chit how SAX Parser works!!!

Upvotes: 1

Related Questions