安卓:我怎样才能显示相同的标签名称的所有XML值 [英] Android: How Can I display all XML values of same tag name

查看:175
本文介绍了安卓:我怎样才能显示相同的标签名称的所有XML值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有FF。从URL的XML:

I have the ff. XML from a URL:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<Phonebook>
    <PhonebookEntry>
        <firstname>Michael</firstname> 
        <lastname>De Leon</lastname> 
        <Address>5, Cat Street</Address> 
    </PhonebookEntry>
    <PhonebookEntry>
        <firstname>John</firstname> 
        <lastname>Smith</lastname> 
        <Address>6, Dog Street</Address> 
    </PhonebookEntry>
</Phonebook>

我想同时显示PhonebookEntry值(名字,姓氏,地址)。目前,我的code只显示约翰·史密斯的PhonebookEntry(最后一项)。这是我的code。

I want to display both PhonebookEntry values (firstname,lastname,Address). Currently, my code displays only the PhonebookEntry of John Smith (the last entry). Here's my code.

ParsingXML.java

package com.example.parsingxml;

import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
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://somedomain.com/jm/sampleXML.xml");
              URLConnection ucon = 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. */
              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 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_firstname = false;
     private boolean in_lastname= false;
     private boolean in_Address=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("PhoneBook")) {
            this.in_outertag = true;
        }else if (localName.equals("PhonebookEntry")) {
            this.in_innertag = true;
        }else if (localName.equals("firstname")) {
            this.in_firstname = true;
        }else if (localName.equals("lastname"))  {
            this.in_lastname= true;
        }else if(localName.equals("Address"))  {
            this.in_Address= true;
        } 

     }

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

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          if(this.in_firstname){
          myParsedExampleDataSet.setfirstname(new String(ch, start, length));
          }
          if(this.in_lastname){
          myParsedExampleDataSet.setlastname(new String(ch, start, length));
          }
          if(this.in_Address){
              myParsedExampleDataSet.setAddress(new String(ch, start, length));
          }
    }
}

ParsedExampleDataSet.java

package com.example.parsingxml;

public class ParsedExampleDataSet {
    private String firstname = null;
    private String lastname=null;
    private String Address=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;
    }

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

    }
}

我是新来的Java和Android开发人员,许多在此先感谢您的帮助! :)

I'm new to java and android dev, many thanks in advance for any help! :)

推荐答案

其他的反应已经指出的那样,你需要一个列表来存储所有的 ParsedExampleDataSet 物体得到该XML。

The other responses have already pointed out that you require a list to store all the ParsedExampleDataSet objects gotten from the XML.

不过,我想指出你注意的另一件事有关XML处理程序可能只是后来(随机)咬你。字符的方法是不是个好地方分配标签,你XML之间找到的值,因为该字符的方法不能保证一次返回所有字符中的一个元素。它可以叫做同一元件内多次报告到目前为止找到的字符。您的实现,因为它是现在,你将最终获得丢失的数据,不知道是怎么回事。

But I want to point your attention to another thing about XML handlers which may bite you only later (and randomly). The characters method is not a good place to assign the values found between tags in you XML, because the characters method is not guaranteed to return all the characters in an element at once. It may be called multiple times within the same element to report characters found so far. With your implementation as it is right now, you will end up with missing data and wonder what is going on.

这是说,我会做什么它使用的StringBuilder 来积累你的人物,然后在的endElement(...),为它们分配通话。像这样:

That said, what I would do it use a StringBuilder to accumulate your characters and then assign them in an endElement(...) call. Like so:

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

您就可以检索您的活动ParsedExampleDataSets列表,或者显示在多个文本视图或只有一个。你的 Activity.onCreate(...)方法可能如下:

You can then retrieve the list of ParsedExampleDataSets in your activity and either display in multiple text views or only in one. Your Activity.onCreate(...) method may look like:

/** 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://somedomain.com/jm/sampleXML.xml");
              URLConnection ucon = url.openConnection();

              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();

              //remember to import android.util.Xml
              Xml.parse(url.openStream(), Xml.Encoding.UTF_8, myExampleHandler);


              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSetList =
                                            myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              for(ParsedExampleDataSet parsedExampleDataSet : parsedExampleDataSetList){
                  tv.append(parsedExampleDataSet.toString());
              }

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

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

这篇关于安卓:我怎样才能显示相同的标签名称的所有XML值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆