Android:如何检索已解析的值

时间:2011-05-05 09:25:21

标签: java android xml loops

我想在onc​​reate方法中使用 for循环或while循环检索解析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值中的文件。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,那么您要做的是在解析完成后循环遍历您的parsedExampleDataSet列表并打印出其中保存的值。目前,您使用toString()方法打印List的内容,这显然不太理想。好。

我建议您使用Iterator。 Iterator是一个非常有用的对象,您可以从List中获取该对象以便对该List进行迭代或循环。

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

我要在这里输入的内容不是经过全面测试或正常工作的代码;它只是给你一个基本的想法。

首先定义迭代器:

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.

显然你在while循环中使用.getFileURL(),. getAddress等返回的字符串做什么取决于你的特定UI。在我的小例子中,我将URL和地址覆盖到同一个TextView中;但它的目的是展示循环遍历List数据集的概念。