我为孩子制作了一个小型测试程序。我想学习他的数学。
面对从XML文件读取问题的问题
<?xml version="1.0" encoding="utf-8"?>
<questions>
<question>
<vopros>How much will 2+2?</vopros>
<otvet_1>2</otvet_1>
<otvet_2>6</otvet_2>
<otvet_3>8</otvet_3>
<otvet_4 name="pravilno">4</otvet_4>
</question>
<question>
<vopros>How much will 3+3?</vopros>
<otvet_1>12</otvet_1>
<otvet_2>16</otvet_2>
<otvet_3>18</otvet_3>
<otvet_4 name="pravilno">6</otvet_4>
</question>
<question>
<vopros>How much is 4+4?</vopros>
<otvet_1>22</otvet_1>
<otvet_2>26</otvet_2>
<otvet_3>18</otvet_3>
<otvet_4 name="pravilno">8</otvet_4>
</question>
<question>
<vopros>How much is 5+5?</vopros>
<otvet_1>2</otvet_1>
<otvet_2>6</otvet_2>
<otvet_3>8</otvet_3>
<otvet_4 name="pravilno">10</otvet_4>
</question>
</questions>
我需要激活vopros3并回答选项(otvet_1,otvet_2,otvet_3,otvet_4)
从XML文件检索数据的Java代码
try {
XmlPullParser parser = getResources().getXml(R.xml.voprosi);
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() == XmlPullParser.START_TAG
&& parser.getName().equals("question")) {
if(numvopr==3)
{
// ....... here it is necessary to withdraw a question and answers
Question.setText(...);
answ1.setText(...);
answ2.setText(...);
answ3.setText(...);
answ4.setText(...);
}
numvopr++;
}
parser.next();
}
} catch (Throwable t) {
Toast.makeText(this,
"XML Error: " + t.toString(),
Toast.LENGTH_LONG).show();
}
最佳答案
实现为状态机的一种方法:
String lastStartTag = "";
// change to desired question - 0-based
int targetQuestion = 3;
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
// Count questions and record every START tag
if (parser.getEventType() == XmlPullParser.START_TAG) {
lastStartTag = parser.getName();
if (parser.getName().equals("question")) {
numvopr++;
}
}
// Process text based on whether we are at desired question
// and last processed START tag.
else if (parser.getEventType() == XmlPullParser.TEXT) {
if (numvopr == targetQuestion) {
if (lastStartTag.compareTo("vopros") == 0) {
Question.setText(parser.getText());
}
else if (lastStartTag.compareTo("otvet_1") == 0) {
answ1.setText(parser.getText());
}
else if (lastStartTag.compareTo("otvet_2") == 0) {
answ2.setText(parser.getText());
}
else if (lastStartTag.compareTo("otvet_3") == 0) {
answ3.setText(parser.getText());
}
else if (lastStartTag.compareTo("otvet_4") == 0) {
answ4.setText(parser.getText());
}
}
}
parser.next();
}
关于android - 如何从XML文件中选择特定元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55341307/