我想显示XML" category"的值。 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文件位于项目的资源文件夹中。有人可以帮忙吗?
提前谢谢!