1

我想在 .xml 文件中显示 XML“类别”标签的值Spinner。我找不到XmlPullParser工作,我总是得到XmlPullParserException。我有这个 XML 解析器类:

public class XmlCategoryParser {

private static final String ns = null;

public List<String> parse(InputStream in) throws XmlPullParserException, IOException {
    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
        return readFeed(parser);
    } finally {
        in.close();
    }
}

// Processing the feed
private List<String> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
    List<String> categories = new ArrayList<String>();

    parser.require(XmlPullParser.START_DOCUMENT, ns, "feed");
    while (parser.next() != XmlPullParser.END_DOCUMENT) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        // Starts by looking for the category tag
        if (name.equals("category")) {
            categories.add(readCategory(parser));
        } else {
            skip(parser);
        }
    }  
    return categories;
}

// Processes category tags in the feed.
private String readCategory(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "category");
    String category = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "category");
    return category;
}

// Extracts text values of category tags.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
    String result = "";
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.getText();
        parser.nextTag();
    }
    return result;
}

// Skips tags that are not interested.
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
        throw new IllegalStateException();
    }
    int depth = 1;
    while (depth != 0) {
        switch (parser.next()) {
        case XmlPullParser.END_TAG:
            depth--;
            break;
        case XmlPullParser.START_TAG:
            depth++;
            break;
        }
    }
 }

}

MainActivity课堂上,我有:

public void addItemsOnSpinner() {
    XmlCategoryParser categoryParser = new XmlCategoryParser();
    List<String> categories = null;
    InputStream inputStream = null;

    try {
        inputStream = getAssets().open(FILENAME);
        categories = categoryParser.parse(inputStream);
    } catch (FileNotFoundException e) {
        // ...
    } catch (IOException e) {
        // ...
    } catch (XmlPullParserException e) {
        // ...
    }

}

我总是收到一条XmlPullParserException错误消息,并且我的类别列表为空(返回 null)。我的 XML 文件位于项目的 assets 文件夹中。任何人都可以帮忙吗?
先感谢您!

4

0 回答 0