2015-05-12 58 views
-1

我使用本教程http://www.androidbegin.com/tutorial/android-xml-parse-images-and-texts-tutorial/到達XML解析,如果我想要將URL更改爲這個http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml,該怎麼做?因爲xml格式不同。如果有類似的問題請告訴我。謝謝。Android XML解析列表視圖

每個listitem都有一個標籤,但我的網址只有'Infos'開頭,包含所有標籤。

MainActivity.java

package eason.xml; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.ListView; 

import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 

import java.io.IOException; 
import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Map; 

public class MainActivity extends Activity { 
    // Declare Variables 
    ListView listview; 
    ListViewAdapter adapter; 
    ProgressDialog mProgressDialog; 
    ArrayList<HashMap<String, String>> arraylist; 

    static String ID = "Id"; 
    static String NAME = "Name"; 
    static String WEBSITE = "Website"; 
    static String PICTURE1 = "Picture"; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Get the view from listview_main.xml 
     setContentView(R.layout.listview_main); 
     // Execute DownloadJSON AsyncTask 
     new DownloadXML().execute(); 
    } 

    // DownloadJSON AsyncTask 
    private class DownloadXML extends AsyncTask<Void, Void, Void> { 
     private void parseRequestResultXML(InputStream stream) { 

      arraylist=new ArrayList<HashMap<String,String>>(); 

      try { 
       XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
       XmlPullParser parser = factory.newPullParser(); 
       parser.setInput(stream, null); 

       HashMap<String, String> map = null; 

       int eventType = parser.getEventType(); 
       while (eventType != XmlPullParser.END_DOCUMENT) { 
        switch (parser.getEventType()) { 

         case XmlPullParser.START_DOCUMENT: 
          //Log.i("TAG", " Start document " + parser.getName()); 
          break; 

         case XmlPullParser.START_TAG: 
          //Log.i("TAG", " Start tag " + parser.getName()); 
          String tag=parser.getName(); 

          if(tag.equals("Info")){ //read values from Info tag 
           Log.i("TAG","reading info"); 
           ID=parser.getAttributeValue(null, "Id"); 
           NAME=parser.getAttributeValue(null, "Name"); 
           WEBSITE=parser.getAttributeValue(null, "Website"); 
           PICTURE1=parser.getAttributeValue(null,"Picture1"); 
           //do same for other values 

           map = new HashMap<String, String>(); 
           map.put("Id", ID); 
           map.put("Name", NAME); 
           map.put("Website", WEBSITE); 
           arraylist.add(map); 
          } 

          break; 

         case XmlPullParser.END_TAG: 
          //Log.i("TAG", " End tag " + parser.getName()); 
          break; 

         default: 
          break; 
        } 
        eventType=parser.next(); //get next event type 
       } 

       //reading all values from list 
       for (Map<String,String> e : arraylist) { 
        Log.d("TAG"," Row ID "+e.get("Id")+" Name "+e.get("Name")+" Website "+e.get("Website")+" Picture1 "+e.get("Picture1")); 
       } 

      } catch (XmlPullParserException e) { 
       e.printStackTrace(); 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
      } 

     } 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Create a progressdialog 
      mProgressDialog = new ProgressDialog(MainActivity.this); 
      // Set progressdialog title 
      mProgressDialog.setTitle("Android XML Parse Tutorial"); 
      // Set progressdialog message 
      mProgressDialog.setMessage("Loading..."); 
      mProgressDialog.setIndeterminate(false); 
      // Show progressdialog 
      mProgressDialog.show(); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      // Create an array 
      arraylist = new ArrayList<HashMap<String, String>>(); 
      XMLParser parser = new XMLParser(); 
// Retrieve nodes from the given URL address 
      InputStream stream = parser.getInputStreamFromUrl("http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml"); 
      if (stream != null) { 
       try {parseRequestResultXML(stream); 
       stream.close();}catch(IOException e1) { 
        e1.printStackTrace(); 
       } 
      }return null; 
     } 
     @Override 
     protected void onPostExecute(Void args) { 
      // Locate the listview in listview_main.xml 
      listview = (ListView) findViewById(R.id.listview); 
      // Pass the results into ListViewAdapter.java 
      adapter = new ListViewAdapter(MainActivity.this, arraylist); 
      // Binds the Adapter to the ListView 
      listview.setAdapter(adapter); 
      // Close the progressdialog 
      mProgressDialog.dismiss(); 
     } 

}} 

ListViewAdapter

package eason.xml; 

import android.content.Context; 
import android.content.Intent; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 

import java.util.ArrayList; 
import java.util.HashMap; 

public class ListViewAdapter extends BaseAdapter { 

    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ArrayList<HashMap<String, String>> data; 
    ImageLoader imageLoader; 
    HashMap<String, String> resultp = new HashMap<String, String>(); 

    public ListViewAdapter(Context context, 
          ArrayList<HashMap<String, String>> arraylist) { 
     this.context = context; 
     data = arraylist; 
     imageLoader = new ImageLoader(context); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     // Declare Variables 
     TextView NAME; 
     TextView START; 
     TextView WEBSITE; 
     ImageView Picture1; 

     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View itemView = inflater.inflate(R.layout.listview_item, parent, false); 
     // Get the position 
     resultp = data.get(position); 

     // Locate the TextViews in listview_item.xml 
     NAME = (TextView) itemView.findViewById(R.id.rank); 
     START = (TextView) itemView.findViewById(R.id.country); 
     WEBSITE = (TextView) itemView.findViewById(R.id.population); 

     // Locate the ImageView in listview_item.xml 
     Picture1 = (ImageView) itemView.findViewById(R.id.flag); 

     // Capture position and set results to the TextViews 
     NAME.setText(resultp.get(MainActivity.ID)); 
     START.setText(resultp.get(MainActivity.NAME)); 
     WEBSITE.setText(resultp.get(MainActivity.WEBSITE)); 
     // Capture position and set results to the ImageView 
     // Passes flag images URL into ImageLoader.class 
     imageLoader.DisplayImage(resultp.get(MainActivity.PICTURE1), Picture1); 
     // Capture ListView item click 
     itemView.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // Get the position 
       resultp = data.get(position); 
       Intent intent = new Intent(context, SingleItemView.class); 
       // Pass all data rank 
       intent.putExtra("Id", resultp.get(MainActivity.ID)); 
       // Pass all data country 
       intent.putExtra("Name", resultp.get(MainActivity.NAME)); 
       // Pass all data population 
       intent.putExtra("Website", 
         resultp.get(MainActivity.WEBSITE)); 
       // Pass all data flag 
       intent.putExtra("Picture1", resultp.get(MainActivity.PICTURE1)); 
       // Start SingleItemView Class 
       context.startActivity(intent); 

      } 
     }); 
     return itemView; 
    } 
} 

XML解析器

package eason.xml; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.w3c.dom.Document; 
import org.w3c.dom.Node; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.StringReader; 
import java.io.UnsupportedEncodingException; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

public class XMLParser { 

    public XMLParser() { 

    } 

    // Retrive XML from URL 
    public String getXmlFromUrl(String url) { 
     String xml = null; 

     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      xml = EntityUtils.toString(httpEntity); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return xml; 
    } 

    // Retrive DOM element 
    public Document getDomElement(String xml) { 
     Document doc = null; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     try { 

      DocumentBuilder db = dbf.newDocumentBuilder(); 

      InputSource is = new InputSource(); 
      is.setCharacterStream(new StringReader(xml)); 
      doc = db.parse(is); 

     } catch (ParserConfigurationException e) { 
      Log.e("Error: ", e.getMessage()); 
      return null; 
     } catch (SAXException e) { 
      Log.e("Error: ", e.getMessage()); 
      return null; 
     } catch (IOException e) { 
      Log.e("Error: ", e.getMessage()); 
      return null; 
     } 

     return doc; 
    } 

    // Retrive Node element 
    public final String getElementValue(Node elem) { 
     Node child; 
     if (elem != null) { 
      if (elem.hasChildNodes()) { 
       for (child = elem.getFirstChild(); child != null; child = child 
         .getNextSibling()) { 
        if (child.getNodeType() == Node.TEXT_NODE) { 
         return child.getNodeValue(); 
        } 
       } 
      } 
     } 
     return ""; 
    } 

    // Retrive Node Value 
    public InputStream getInputStreamFromUrl(String url) { 
     String xml = null; 
     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      return httpEntity.getContent(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 
+0

爲什麼負面的評價,爲什麼不?你發表評論? –

+0

更改getXmlFromUrl中的URL? – natario

+0

您是否注意到標籤格式不同? –

回答

1

變化getXmlFromUrl()的URL,然後更改parser.getValue(e, **RANK**)鍵。無論您的格式是什麼,您都需要指定密鑰來獲取數據,然後進行相應的保存。

+0

不起作用,開始標記是不同。 –

+0

你需要改變鑰匙來獲取數據。它的新標籤是信息,然後你可以像這樣檢查if(tag.equals(「Info」))。一切都寫在你的代碼中。 –

1

在該教程中,作者正在讀取XML的TEXT標記的值。但在你的情況下,你需要從那裏獲取屬性名稱的值。

private void parseRequestResultXML(InputStream stream) { 

     arraylist=new ArrayList<HashMap<String,String>>(); 

     try { 
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
      XmlPullParser parser = factory.newPullParser(); 
      parser.setInput(stream, null); 

      HashMap<String, String> map = null; 

      int eventType = parser.getEventType(); 
      while (eventType != XmlPullParser.END_DOCUMENT) { 
       switch (parser.getEventType()) { 

       case XmlPullParser.START_DOCUMENT: 
        //Log.i("TAG", " Start document " + parser.getName()); 
        break; 

       case XmlPullParser.START_TAG: 
        //Log.i("TAG", " Start tag " + parser.getName()); 
        String tag=parser.getName(); 

        if(tag.equals("Info")){ //read values from Info tag 
         Log.i("TAG","reading info"); 
         String id=parser.getAttributeValue(null, "Id"); 
         String name=parser.getAttributeValue(null, "Name"); 
         String website=parser.getAttributeValue(null, "Website"); 
         //do same for other values 

         map = new HashMap<String, String>(); 
         map.put("id", id); 
         map.put("name", name); 
         map.put("website", website); 
         arraylist.add(map); 
        } 

        break; 

       case XmlPullParser.END_TAG: 
        //Log.i("TAG", " End tag " + parser.getName()); 
        break; 

       default: 
        break; 
       } 
       eventType=parser.next(); //get next event type 
      } 

      //reading all values from list 
      for (Map<String,String> e : arraylist) { 
       Log.d("TAG"," Row ID "+e.get("id")+" Name "+e.get("name")+" Website "+e.get("website")); 
      } 

     } catch (XmlPullParserException e) { 
      e.printStackTrace(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 

    } 

更新:XMLParser.java

public InputStream getInputStreamFromUrl(String url) { 
     String xml = null; 
     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      return httpEntity.getContent(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

添加這種方法在doInBackground

arraylist = new ArrayList<HashMap<String, String>>(); 
XMLParser parser = new XMLParser(); 
// Retrieve nodes from the given URL address 
InputStream stream = parser.getInputStreamFromUrl("http://www.androidbegin.com/tutorial/xmlparseimgtxt.xml"); 
if (stream != null){ 
    parseRequestResultXML(stream); 
    stream.close(); 
} 

Happy_Coding ... :)

+0

Thanks.But我不知道應該從代碼中替換哪一行。 –

+0

僅以inputstream作爲參數調用方法。 – Bharatesh

+0

只需將所有這些代碼放入mainActivity? –