【发布时间】:2014-03-17 21:50:49
【问题描述】:
我有一些如下所示的 XML
<question id="0">
<text>
Who is the first President of the United States of America?
</text>
<image>
http://upload.wikimedia.org/wikipedia/commons/b/b6/Gilbert_Stuart_Williamstown_Portrait_of_George_Washington.jpg
</image>
<choices>
<choice answer="true">George Washington</choice>
<choice>Thomas Jefferson</choice>
<choice>James Monroe</choice>
<choice>John Adams</choice>
</choices>
</question>
我正在尝试将其解析为一些对象。目前,我有一个while循环,当解析器检查if"choices"是当前标签时,它会进入并启动while循环以获取所有选择标签并从中生成对象。
QuestionUtil
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
public class QuestionUtil {
static ArrayList<Question> parseQuestions(InputStream xmlIn) throws XmlPullParserException, IOException {
XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(xmlIn, "UTF-8");
Question question = null;
ArrayList<Question> questionList = new ArrayList<Question>();
Choices choices = null;
ArrayList<Choices> choiceList = new ArrayList<Choices>();
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
if(parser.getName().equals("question")) {
question = new Question();
try {
question.setId(parser.getAttributeValue(null, "id"));
}
catch (NumberFormatException ex) { }
}
else if (parser.getName().equals("text")) {
question.setText(parser.nextText());
}
else if (parser.getName().equals("image")) {
question.setImage(parser.nextText());
}
else if (parser.getName().equals("choices")) {
boolean isCorrect;
String answer;
parser.next();
/**** (BELOW) THIS PART IS NOT WORKING PROPERLY ****/
// parser.getName().equals("choice")
while ("choice".equals(parser.getName())) {
if (parser.getAttributeValue(null, "answer") != null) {
isCorrect = true;
answer = parser.nextText();
choices = new Choices(isCorrect, answer);
}
else {
isCorrect = false;
answer = parser.nextText();
choices = new Choices(isCorrect, answer);
}
choiceList.add(choices);
parser.next();
// Testing purposes
Log.d("demo", answer + " " + isCorrect);
}
/**** (ABOVE) THIS PART IS NOT WORKING PROPERLY ****/
question.setChoices(choiceList);
} // END Choices Parsing
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("question")) {
questionList.add(question);
question = null;
}
break;
default:
break;
} // END Switch
event = parser.next();
} // END While loop
return questionList;
}
}
谁能帮我弄清楚为什么它不起作用?一旦我有一个if 语句来检查"choices" 标签,我就继续前进,parser.next() 转到下一行,应该是"choice"。并不总是有四个选择,可能或多或少,这就是为什么我需要能够循环通过它。
【问题讨论】:
-
您不需要在“选择”项的循环中添加
case XmlPullParser.START_TAG吗? -
像嵌套的
case XmlPullParser.START_TAG:你的意思是?我想这是可能的,我会研究一下。
标签: android xml-parsing xmlpullparser