我有以下 XML
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<questions>
<question topic="net">
<questiontext>Which of the following applies to TCP?</questiontext>
<answers correct="true">
<answer correct="true">reliable</answer>
<answer correct="false">connectionless</answer>
<answer correct="true">connection-oriented</answer>
<answer correct="false">datagram-based</answer>
</answers>
</question>
</questions>
我正在尝试使用以下代码对其进行解析,以获取“answer”元素上“正确”属性的值
private ArrayList<MCAnswer> readAnswers(XmlPullParser parser) throws IOException, XmlPullParserException {
// create an ArrayList to which MCAnswers will be added below
ArrayList<MCAnswer> answers = new ArrayList<MCAnswer>();
// starting at the <answers> element...
parser.require(XmlPullParser.START_TAG, ns, "answers");
// loop through the individual <answer> elements
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
// read in answer text
String answerText = readText(parser);
// TODO how to get value of "correct" attribute of <answer>?
//debugging variables
int numOfAttrs = parser.getAttributeCount(); //returns -1, not right!
String element = parser.getName(); //returns "answer", right!
String attr = parser.getAttributeValue(ns, "correct"); //returns null, not right!
}
return answers;
}
我的问题是 String attr = parser.getAttributeValue(ns, "correct"); 我希望它返回值“true”或“false”,但它返回 null,好像解析器找不到属性,上面的 getAttributeValues() 也返回 -1(IndexOutOfBoundsError?)但似乎我是正确的标记为 getName() 和节点文本返回正确的值。
我做错了什么阻止我访问该属性?