1

我一直在尝试在我的 Android 应用程序中实现 XML 阅读器,但是我一直在尝试使用的 SAX 解析器没有返回我期望的结果。解析器应该返回一个带有字符串的字符串,即“标题”。

我使用以下作为我的解析器实现:

import java.util.ArrayList;

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

import android.util.Log;

public class NewsParser extends DefaultHandler {
    boolean title = false;
    boolean body = false;
    boolean image = false;
    String titleString;
    String bodyString;
    String imageString;

    ArrayList<NewsItem> newsList = new ArrayList<NewsItem>();

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

        Log.i("TestD", "Tag Name:" + qName);

        if (qName.equalsIgnoreCase("title")) {
            title = true;
        }

        if (qName.equalsIgnoreCase("body")) {
            body = true;
        }

        if (qName.equalsIgnoreCase("image")) {
            image = true;
        }

    }

    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (qName.equalsIgnoreCase("item")) {
            NewsItem newsItem = new NewsItem();
            newsItem.setContent(bodyString);
            newsItem.setTitle(titleString);
            newsItem.setImage(imageString);
            newsList.add(newsItem);
        }

    }

    public void characters(char ch[], int start, int length)
            throws SAXException {
        Log.i("TestD", new String(ch, start, length) + " with "
                + String.valueOf(body) + " & " + String.valueOf(title) + " & "
                + String.valueOf(image));

        if (title) {
            titleString = new String(ch, start, length);
            title = false;
        }

        if (body) {
            bodyString = new String(ch, start, length);
            body = false;
        }

        if (image) {
            imageString = new String(ch, start, length);
            image = false;
        }

    }
}

和我试图阅读的 XML(远程托管):

<news>
<item>
<title>Year 10 History Trip to Berlin</title>
<body>
This will be the body</body>
<image>
http://upload.wikimedia.org/wikipedia/commons/5/52/Berlin_Montage_4.jpg
</image>
</item>
</news>

我还包括了一些“Logcat”消息传递区域,它们返回以下内容:

 with false & false & false
Tag Name:item

 with false & false & false
Tag Name:title

 with false & true & false
Year 10 History Trip to Berlin with false & false & false

 with false & false & false

 with false & false & false
Tag Name:body

 with true & false & false
This will be the body

 with false & false & false

 with false & false & false
Tag Name:image

 with false & false & true

 http://upload.wikimedia.org/wikipedia/commons/5/52/Berlin_Montage_4.jpg with false & false & false

 with false & false & false

 with false & false & false

 with false & false & false

正如您从我的代码中看到的那样,我正在尝试获取 XML 标记内容并使用结果“创建”一个 NewsItem,但是 NewsItem 只有一个空间,其中包含标题、内容或图像。

我希望我已经正确解释了我的问题,任何帮助将不胜感激!

4

0 回答 0