0

現在、アイテムノード内の要素を処理しようとしています。この時点では簡単にするためにタイトルだけに注目していますが、解析すると、同じ要素が 3 回取得されていることがわかります。

http://open.live.bbc.co.uk/weather/feeds/en/2643123/3dayforecast.rss

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

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

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

import android.util.Log;

public class XMLHelper extends DefaultHandler {
    private String URL_Main="http://open.live.bbc.co.uk/weather/feeds/en/2643123/3dayforecast.rss";
    String TAG = "XMLHelper";

    Boolean currTag = false;
    String currTagVal = "";     

    public ItemData item = null;
    public ArrayList<ItemData> items = new ArrayList<ItemData>();

    public void get() {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(this);
            InputStream inputStream = new URL(URL_Main).openStream();
            reader.parse(new InputSource(inputStream));
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    // Receives notification of the start of an element

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        Log.i(TAG, "TAG: " + localName);

        currTag = true;
        currTagVal = "";
        if (localName.equals("channel")) {
            item = new ItemData();
        }

    }

    // Receives notification of end of element

    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currTag = false;

        if (localName.equalsIgnoreCase("title"))
            item.setTitle(currTagVal);


        else if (localName.equalsIgnoreCase("item"))
            items.add(item);


    }

    // Receives notification of character data inside an element 

    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currTag) {
            currTagVal = currTagVal + new String(ch, start, length);

            currTag = false;
        }

    }
}
4

2 に答える 2

0

同じ値を 3 回取得する理由は、メソッドにchannelタグがあるときにオブジェクトを作成しているためです。startElement

    if (localName.equals("channel")) {
        item = new ItemData();
    }

以下のようにアイテムタグがあるときはいつでもオブジェクトを開始する必要があると思います

    if (localName.equals("item")) { // check for item tag
        item = new ItemData();
    }
于 2013-08-13T02:08:29.867 に答える