2013-10-17 53 views
0

的XML是http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0無法使用SAX

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

解析XML網頁我試圖讀取屬性LATLON的值。

這是我的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"); 
    } 

這是SAXHandler類:

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")) { 

      } 
     } 
    } 

} 

這是ParsedXMLDataSet類:

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

我無法弄清楚什麼是錯的。我看到的只是Logcat中的「失敗」。 e.getMessage()爲空。

回答

1

嘗試下面的代碼..

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(); 


     } 

    } 
} 

編輯在您的疑問句

  if (localName.equals("rsp")) { 

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

@ArjunU後然後我檢查我只貼到你...然後在比較的代碼,這是更容易和有幫助。 – Hariharan

+0

@ArjunU我檢查它肯定會顯示..你有你的清單給互聯網許可。 – Hariharan

+0

@ArjunU檢查我的編輯從您的代碼將顯示.. – Hariharan