在android中从Internet读取XML

时间:2013-11-21 14:22:55

标签: android xml

如何使用android从互联网上检索xml的所有值。我找到了一个很好的教程并实现了它http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html,但我只能检索我的xml的最后一项:(我想在简单的ListView中显示结果

这是我在互联网http://www.rahmanrahim.com/webservicekos/allkos托管的xml文件(抱歉,我无法正确发布)

这是我的MainActivity.java

package com.example.cobaxmlparser;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

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

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {



/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);
    /* Create a new TextView to display the parsingresult later. */
    TextView tv = new TextView(this);
    ListView view = (ListView) findViewById(R.id.view);
    String[] hasilXml = new String[21];
    int x = 0;
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    try {
        /* Create a URL we want to load some xml-data from. */
        URL url = new URL("http://www.rahmanrahim.com/webservicekos/allkos");
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        //URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestMethod("GET");

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

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();
        /* Create a new ContentHandler and apply it to the XML-Reader*/ 
        ExampleHandler myExampleHandler = new ExampleHandler();
        xr.setContentHandler(myExampleHandler);

        /* Parse the xml-data from our URL. */
        xr.parse(new InputSource(url.openStream()));
        /* Parsing has finished. */

        /* Our ExampleHandler now provides the parsed data to us. */
        ParsedExampleDataSet parsedExampleDataSet = 
                                myExampleHandler.getParsedData();

        /* Set the result to be displayed in our GUI. */
        //tv.setText(parsedExampleDataSet.toString());
        //String cek = parsedExampleDataSet.toString(x);
        hasilXml[x] = parsedExampleDataSet.toString();
        x++;
        System.out.println("nilai x adalah : " + x);
        //tv.setText(cek);


    } catch (Exception e) {
        /* Display any Error to the GUI. */
        tv.setText("Error: " + e.getMessage());
        Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
    }
    /* Display the TextView. */
    //this.setContentView(tv);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hasilXml);
    view.setAdapter(adapter);
}

}

这是我的ExampleHandler.java

 package com.example.cobaxmlparser;


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


public class ExampleHandler extends DefaultHandler{

// ===========================================================
// Fields
// ===========================================================

private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_id_kos = false;
private boolean in_nama = false;
private boolean in_latitude = false;
private boolean in_longitude = false;
private boolean in_harga = false;
private boolean in_tampakdepan = false;
private boolean in_streetview = false;
private boolean in_alamat = false;




private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();

// ===========================================================
// Getter & Setter
// ===========================================================

public ParsedExampleDataSet getParsedData() {
    return this.myParsedExampleDataSet;
}

// ===========================================================
// Methods
// ===========================================================
@Override
public void startDocument() throws SAXException {
    this.myParsedExampleDataSet = new ParsedExampleDataSet();
}

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

/** Gets be called on opening tags like: 
 * <tag> 
 * Can provide attribute(s), when xml was like:
 * <tag attribute="attributeValue">*/
@Override
public void startElement(String namespaceURI, String localName,
        String qName, Attributes atts) throws SAXException {
    if(localName.equals("xml"))
    {
        this.in_outertag = true;
    }
    else if (localName.equals("item")) {
        this.in_innertag = true;

    }else if (localName.equals("id_kos")) {
        this.in_id_kos = true;
    }else if (localName.equals("nama"))
    {
        this.in_nama = true;
    }else if (localName.equals("alamat"))
    {
        this.in_alamat = true;
    }else if (localName.equals("latitude"))
    {
        this.in_latitude = true;
    }else if (localName.equals("longitude"))
    {
        this.in_longitude = true;
    }else if (localName.equals("harga"))
    {
        this.in_harga = true;
    }else if (localName.equals("tampakdepan"))
    {
        this.in_tampakdepan = true;
    }else if (localName.equals("streetview"))
    {
        this.in_streetview = true;
    }
    }



/** Gets be called on closing tags like: 
 * </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
        throws SAXException {
    if(localName.equals("xml"))
    {
        this.in_outertag = false;
    }
    else if (localName.equals("item")) {
        this.in_innertag = false;

    }else if (localName.equals("id_kos")) {
        this.in_id_kos = false;
    }else if (localName.equals("nama"))
    {
        this.in_nama = false;
    }else if (localName.equals("alamat"))
    {
        this.in_alamat = false;
    }else if (localName.equals("latitude"))
    {
        this.in_latitude = false;
    }else if (localName.equals("longitude"))
    {
        this.in_longitude = false;
    }else if (localName.equals("harga"))
    {
        this.in_harga = false;
    }else if (localName.equals("tampakdepan"))
    {
        this.in_tampakdepan = false;
    }else if (localName.equals("streetview"))
    {
        this.in_streetview = false;
    }

}

/** Gets be called on the following structure: 
 * <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {
    if(this.in_id_kos){
        myParsedExampleDataSet.setId_kos(new String(ch, start, length));
    }if(this.in_nama){
        myParsedExampleDataSet.setNama(new String(ch, start, length));
    }if(this.in_alamat){
        myParsedExampleDataSet.setAlamat(new String(ch, start, length));
    }if(this.in_latitude){
        myParsedExampleDataSet.setLatitude(new String(ch, start, length));
    }if(this.in_longitude){
        myParsedExampleDataSet.setLongitude(new String(ch, start, length));
    }if(this.in_harga){
        myParsedExampleDataSet.setHarga(new String(ch, start, length));
    }if(this.in_tampakdepan){
        myParsedExampleDataSet.setTampakdepan(new String(ch, start, length));
    }if(this.in_streetview){
        myParsedExampleDataSet.setStreetview(new String(ch, start, length));
    }
}

}

和最后一个ParsedExampleDataSet.java

public class ParsedExampleDataSet 
{
private String id_kos = null;
private String nama = null;
private String alamat = null;
private String latitude = null;
private String longitude = null;
private String harga = null;
private String tampakdepan = "";
private String streetview = "";

public String getId_kos() {
return id_kos;
}
public void setId_kos(String id_kos) {
this.id_kos = id_kos;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
    this.nama = nama;
}


public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
    this.latitude = latitude;
}


public String getLongitude() {
    return longitude;
}


public void setLongitude(String longitude) {
    this.longitude = longitude;
}


public String getHarga() {
    return harga;
}


public void setHarga(String harga) {
    this.harga = harga;
}


public String getTampakdepan() {
    return tampakdepan;
}


public void setTampakdepan(String tampakdepan) {
    this.tampakdepan = tampakdepan;
}


public String getStreetview() {
    return streetview;
}


public void setStreetview(String streetview) {
    this.streetview = streetview;
}

public String toString(){


    return "id_kos "+this.id_kos+" nama "+this.nama+" alamat "+this.alamat+" latitude "+this.latitude+" longitude "+this.longitude+" harga "+this.harga+" tampak depan "+this.tampakdepan+" street view "+this.streetview;
}

}

从上面的代码我只能得到最后一项 任何帮助都会很棒。我是android的新手,抱歉我的英文不好。 感谢

2 个答案:

答案 0 :(得分:1)

试试这个..

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

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;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    String url = "http://www.rahmanrahim.com/webservicekos/allkos";
    ProgressDialog pDialog;

    ArrayList<String> hasilXml = new ArrayList<String>();

    ListView view;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = (ListView) findViewById(R.id.view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            new XmlParsing(url).executeOnExecutor(
                    AsyncTask.THREAD_POOL_EXECUTOR, new String[] { null });
        else
            new XmlParsing(url).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("item");

                for (int i = 0; i < nodeList.getLength(); i++) {

                    Node node = nodeList.item(i);

                    Element fstElmnt = (Element) node;
                    NodeList nameList = fstElmnt.getElementsByTagName("id_kos");
                    Element nameElement = (Element) nameList.item(0);
                    nameList = nameElement.getChildNodes();

                    System.out.println("id_kos : "
                            + ((Node) nameList.item(0)).getNodeValue());

                    Element fstElmnt1 = (Element) node;
                    NodeList nameList1 = fstElmnt1.getElementsByTagName("nama");
                    Element nameElement1 = (Element) nameList1.item(0);
                    nameList1 = nameElement1.getChildNodes();

                    System.out.println("nama : "
                            + ((Node) nameList1.item(0)).getNodeValue());

                    Element fstElmnt2 = (Element) node;
                    NodeList nameList2 = fstElmnt2
                            .getElementsByTagName("alamat");
                    Element nameElement2 = (Element) nameList2.item(0);
                    nameList2 = nameElement2.getChildNodes();

                    System.out.println("alamat : "
                            + ((Node) nameList2.item(0)).getNodeValue());

                    Element fstElmnt3 = (Element) node;
                    NodeList nameList3 = fstElmnt3
                            .getElementsByTagName("latitude");
                    Element nameElement3 = (Element) nameList3.item(0);
                    nameList3 = nameElement3.getChildNodes();

                    System.out.println("latitude : "
                            + ((Node) nameList3.item(0)).getNodeValue());

                    Element fstElmnt4 = (Element) node;
                    NodeList nameList4 = fstElmnt4
                            .getElementsByTagName("longitude");
                    Element nameElement4 = (Element) nameList4.item(0);
                    nameList4 = nameElement4.getChildNodes();

                    System.out.println("longitude : "
                            + ((Node) nameList4.item(0)).getNodeValue());

                    Element fstElmnt5 = (Element) node;
                    NodeList nameList5 = fstElmnt5
                            .getElementsByTagName("harga");
                    Element nameElement5 = (Element) nameList5.item(0);
                    nameList5 = nameElement5.getChildNodes();

                    System.out.println("harga : "
                            + ((Node) nameList5.item(0)).getNodeValue());

                    Element fstElmnt6 = (Element) node;
                    NodeList nameList6 = fstElmnt6
                            .getElementsByTagName("tampakdepan");
                    Element nameElement6 = (Element) nameList6.item(0);
                    nameList6 = nameElement6.getChildNodes();

                    System.out.println("tampakdepan : "
                            + ((Node) nameList6.item(0)).getNodeValue());

                    hasilXml.add("id_kos : "
                            + ((Node) nameList.item(0)).getNodeValue()
                            + "nama : "
                            + ((Node) nameList1.item(0)).getNodeValue()
                            + "alamat : "
                            + ((Node) nameList2.item(0)).getNodeValue()
                            + "latitude : "
                            + ((Node) nameList3.item(0)).getNodeValue()
                            + "longitude : "
                            + ((Node) nameList4.item(0)).getNodeValue()
                            + "harga : "
                            + ((Node) nameList5.item(0)).getNodeValue()
                            + "tampakdepan : "
                            + ((Node) nameList6.item(0)).getNodeValue());
                }

            } 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();
             ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, hasilXml);
                view.setAdapter(adapter);
        }

    }
}

答案 1 :(得分:0)

您正在ui线程上运行与网络相关的操作。

移动

HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

threadAsyncTask

解析xml使用XmlPullParser。以下链接中有示例。

http://developer.android.com/training/basics/network-ops/xml.html