Search code examples
androidxmlxml-parsingsax

Unable to parse Web XML using SAX


The XML is at http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0

<rsp stat="ok">
    <cell mnc="45" nbSamples="3" lac="10113" mcc="404" lat="12.9929332248439" cellId="13113" range="6000" lon="77.5656492910538"/>
</rsp>

I'm trying to read values of attributes lat and lon.

This is in my MainActivity:

try {

        URL url = new URL(
                "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0");


        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        SAXHandler mySAXHandler = new SAXHandler();
        xr.setContentHandler(mySAXHandler);


        xr.parse(new InputSource(url.openStream()));



        Log.i("msg", "success");
    } catch (Exception e) {

        Log.i("msg", "fail");
    }

This is the SAXHandler class:

 public class SAXHandler extends DefaultHandler {

    private ParsedXMLDataSet myParsedXMLDataSet = new ParsedXMLDataSet();

    public ParsedXMLDataSet getParsedData() {
        return this.myParsedXMLDataSet;
    }

    @Override
    public void startDocument() throws SAXException {
        this.myParsedXMLDataSet = new ParsedXMLDataSet();
    }

    @Override
    public void endDocument() throws SAXException {

    }

    @Override
    public void startElement(String namespaceURI, String localName,
            String qName, Attributes atts) throws SAXException {
        if (localName.equals("rsp")) {
            if (localName.equals("cell")) {
                String attrValue1 = atts.getValue("lat");
                String attrValue2 = atts.getValue("lon");
                myParsedXMLDataSet.setExtractedString(attrValue1,
                        attrValue2);
            }
        }
    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName)
            throws SAXException {
        if (localName.equals("rsp")) {
            if (localName.equals("cell")) {

            }
        }
    }

}

This is the ParsedXMLDataSet class:

public class ParsedXMLDataSet {
    private String lat = null, lon = null;

public void setExtractedString(String a, String b) {
    this.lat = a;
    this.lon = b;
}

public String toString() {
    return "Latitude = " + this.lat + "Longitude = " + this.lon;
}
}

I cannot figure out what's wrong. All I see is "fail" in the Logcat. e.getMessage() is blank.


Solution

  • Try the below codes..

    package com.example.xmlparsingasync;
    
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.annotation.TargetApi;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.view.Menu;
    
    public class NetActivity extends Activity {
    
    
        String urls = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
    
        // Progress dialog
        ProgressDialog pDialog;
    
    
    
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_net);
    
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                 new XmlParsing(urls).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
             else
                 new XmlParsing(urls).execute(new String[]{null});
    
    
        }
    
        @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;
        }
    
        public class XmlParsing extends AsyncTask<String, Void, String> {
    
            // variables passed in:
            String urls;
            //  constructor
            public XmlParsing(String urls) {
                this.urls = urls;
            }
    
            @Override
            protected void onPreExecute() {
                pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true);
            }
    
    
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
    
                URL url;
                try {
    
                    url = new URL(urls);
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.parse(new InputSource(url.openStream()));
    
                    doc.getDocumentElement().normalize();
    
                    NodeList nodeList = doc.getElementsByTagName("rsp");
    
                    for (int i = 0; i < nodeList.getLength(); i++) {
    
                        Node node = nodeList.item(i);       
    
                        Element fstElmnt = (Element) node;
                        NodeList nameList = fstElmnt.getElementsByTagName("cell");
                        Element nameElement = (Element) nameList.item(0);
                        nameList = nameElement.getChildNodes();
    
    
                        System.out.println("lat : "+(nameElement.getAttribute("lat")));
                        System.out.println("lon : "+(nameElement.getAttribute("lon")));
    
                    }
    
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SAXException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
    
                return null;
            }
    
            @Override
            protected void onPostExecute(String result) {
                // Now we have your JSONObject, play around with it.
                if (pDialog.isShowing())
                    pDialog.dismiss();
    
    
            }
    
        }
    }
    

    EDIT In your ques

              if (localName.equals("rsp")) {
    
              }
              else if (localName.equals("cell")) {
                    String attrValue1 = atts.getValue("lat");
                    String attrValue2 = atts.getValue("lon");
                    myParsedXMLDataSet.setExtractedString(attrValue1,
                            attrValue2);                
              }