![](/img/trans.png)
[英]Parse an XML having same parent-child tag and then link the value of parent tag to child tag using preferably SAX parser
[英]Parse XML element with same tag using Sax
嗨,大家好,我尝试解析带有相同标签的xml元素时遇到问题
<question id="0">
<text> Who is the first President of the United States of America? </text>
<image> http://liisp.uncc.edu/~mshehab/api/figures/georgewashington.png </image>
<choices>
<choice answer="true">George Washington</choice>
<choice>Thomas Jefferson</choice>
<choice>James Monroe</choice>
<choice>John Adams</choice>
</choices>
</question>
我可以解析所有其他内容,但只能解析最后一个“选择”
这是解析代码的一部分
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equals("text")){
question.setText(xmlInnerText.toString().trim());
} else if(localName.equals("image")){
question.setImageURL(xmlInnerText.toString().trim());
} else if(localName.equals("choices")){
if(localName.equals("choice")){
question.setChoice(xmlInnerText.toString().trim());
}
} else if(localName.equals("question")){
questions.add(question);
}
xmlInnerText.setLength(0);
}
我猜现在正在发生的事情是您正在设置选择,但是随后又重新设置了(替换它)。 因此,您只能获得最后一个。
您必须将每个选择添加到列表中,然后添加question.setChoices(choices)
,其中choices
是一个List。 (当您获得“选择”时,您可以进行choices.add(xmlInnetText.toString().trim());
编辑 :也正如@rmlan所说,看来您永远都不会“选择”。 你并不需要做的if
里面的“选择” if
。 if
s”, if
“选择”可以与其他选择处于同一级别。 除了这个事实以外,上述答案还不错:您需要一个列表来保存每个“选择”。
编辑2 :
您需要这样的东西:
(...)
} else if(localName.equals("choice")) {
choices.add(setChoice(xmlInnerText.toString().trim());
} else if(localName.equals("choices")){
question.setChoices(choices);
}
(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.