2011-05-05 70 views
0

我想取回使用for循環或while循環在onCreate方法我分析我的XML文件後得到的值:安卓:如何檢索解析的值

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<Phonebook> 
    <PhonebookEntry> 
     <firstname>Michael</firstname> 
     <lastname>De Leon</lastname> 
     <Address>5, Cat Street</Address> 
     <FileURL>http://android.mobishark.com/wp-content/uploads/2009/07/android-developers.png</FileURL> 
    </PhonebookEntry> 
    <PhonebookEntry> 
     <firstname>John</firstname> 
     <lastname>Smith</lastname> 
     <Address>6, Dog Street</Address> 
     <FileURL>http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg</FileURL> 
    </PhonebookEntry> 
    <PhonebookEntry> 
     <firstname>Jember</firstname> 
     <lastname>Dowry</lastname> 
     <Address>7, Monkey Street</Address> 
     <FileURL>http://www.techdigest.tv/android.jpg</FileURL> 
    </PhonebookEntry> 
</Phonebook> 

我的代碼:

ParsingXML.java

package com.example.parsingxml; 

import java.net.URL; 
import java.util.List; 

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

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

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
public class ParsingXML extends Activity { 



    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 

     /* Create a new TextView to display the parsingresult later. */ 
     TextView tv = new TextView(this); 
     try { 
       /* Create a URL we want to load some xml-data from. */ 
       URL url = new URL("http://cloud.eacomm.com/jm/sampleXML.xml"); 
       url.openConnection(); 
       /* 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. */ 
       List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData(); 

       /* Set the result to be displayed in our GUI. */ 
       tv.setText(parsedExampleDataSet.toString()); 

     } catch (Exception e) { 
       /* Display any Error to the GUI. */ 
       tv.setText("Error: " + e.getMessage()); 

     } 
     /* Display the TextView. */ 
     this.setContentView(tv); 
    } 
} 

ExampleHandler.java

package com.example.parsingxml; 

import java.util.ArrayList; 
import java.util.List; 

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

public class ExampleHandler extends DefaultHandler{ 

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

    private StringBuilder mStringBuilder = new StringBuilder(); 

    private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet(); 
    private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>(); 

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

    public List<ParsedExampleDataSet> getParsedData() { 
      return this.mParsedDataSetList; 
    } 

    // =========================================================== 
    // Methods 
    // =========================================================== 

    /** 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("PhonebookEntry")) { 
      this.mParsedExampleDataSet = new ParsedExampleDataSet(); 
     } 

    } 

    /** Gets be called on closing tags like: 
     * </tag> */ 
    @Override 
    public void endElement(String namespaceURI, String localName, String qName) 
       throws SAXException { 
      if (localName.equals("PhonebookEntry")) { 
       this.mParsedDataSetList.add(mParsedExampleDataSet); 
      }else if (localName.equals("firstname")) { 
       mParsedExampleDataSet.setfirstname(mStringBuilder.toString().trim()); 
      }else if (localName.equals("lastname")) { 
       mParsedExampleDataSet.setlastname(mStringBuilder.toString().trim()); 
      }else if(localName.equals("Address")) { 
       mParsedExampleDataSet.setAddress(mStringBuilder.toString().trim()); 
      }else if(localName.equals("FileURL")){ 
       mParsedExampleDataSet.setFileURL(mStringBuilder.toString().trim()); 
      } 
      mStringBuilder.setLength(0); 
    } 

    /** Gets be called on the following structure: 
     * <tag>characters</tag> */ 
    @Override 
    public void characters(char ch[], int start, int length) { 
      mStringBuilder.append(ch, start, length); 
    } 
} 

ParsedExampleDataSet.java

package com.example.parsingxml; 

public class ParsedExampleDataSet { 
    private String firstname = null; 
    private String lastname=null; 
    private String Address=null; 
    private String FileURL=null; 


    //Firstname 
    public String getfirstname() { 
     return firstname; 
    } 
    public void setfirstname(String firstname) { 
     this.firstname = firstname; 
    } 

    //Lastname 
    public String getlastname(){ 
     return lastname; 
    } 
    public void setlastname(String lastname){ 
     this.lastname=lastname; 
    } 

    //Address 
    public String getAddress(){ 
     return Address; 
    } 
    public void setAddress(String Address){ 
     this.Address=Address; 
    } 

    //FileURL 
    public String getFileURL(){ 
     return FileURL; 
    } 
    public void setFileURL(String FileURL){ 
     this.FileURL=FileURL; 
    } 

    public String toString(){ 
     return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n"; 
    } 

} 

上述代碼恰好具有FF。輸出:

[Firstname: Michael 
Lastname: De Leon 
Address: 5, Cat Street 
File URL: http://android.mobishark.com/wp-content/uploads/2009/07/android-developers.png 

,Firstname: John 
Lastname: Smith 
Address: 6, Dog Street 
File URL: http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg 

,Firstname: Jember 
Lastname: Dowry 
Address: 7, Monkey Street 
File URL: http://www.techdigest.tv/android.jpg 

] 

我想這樣做的原因是我有一個下載文件類用於下載FileURL值中的文件。

+0

使用Simple XML庫來解析XML:http://massaioli.homelinux.com/wordpress/2011/04/21/simple-xml-in-android-1-5-and-up/ – 2011-05-06 00:54:52

回答

1

如果我正確理解你的問題,你想要做的是在解析完成時循環你的parsedExampleDataSet列表並打印出其中保存的值。目前,您正在使用toString()方法打印List的內容,這顯然不夠理想。好。

我建議你看看使用Iterator。迭代器是一個非常有用的對象,您可以從列表中獲取以迭代或循環該列表。

http://developer.android.com/reference/java/util/ListIterator.html

我要在這裏輸入沒有經過全面測試或工作代碼;這只是給你一個基本的想法。

首先定義一個Iterator:

Iterator i; 

從列表中獲取迭代器:

i = parsedExampleDataSet.iterator(); 

然後你可以使用i.hasNext(),看看是否迭代器有更多元素,並使用i.next()來獲取每個元素。每次調用.next()都會導致迭代器移動到列表中的下一個項目,因此通常需要對該項目進行臨時引用。就像這樣:

ParsedExampleDataSet dataItem; 
while(i.hasNext()){ 

dataItem = i.next(); 
someTextView1.setText(dataItem.getFileURL()); 
anotherTextView.setText(dataItem.getAddress()); 

} 

... etc. 

顯然從.getFileURL(),.getAddress等你回來與絃樂做什麼內部while循環取決於特定的UI。在我的小示例中,我將URL和地址覆蓋到同一個TextView中;然而其目的僅僅是展示循環顯示List數據集的概念。

+0

哇!你的想法和代碼的作品!我只是改變** dataItem = i.next(); **用** dataItem =(ParsedExampleDataSet)i.next(); **用於投射目的。謝啦! :) – Kris 2011-05-06 01:58:55