Reputation: 133
Hi guys i have a problem when i try to parse a xml element with same tag
<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>
I can parse all the others stuff but i can only parse the last "choice"
here is the part of the code for parsing
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);
}
Upvotes: 1
Views: 491
Reputation: 153
I guess what is happening now is that you are setting the choice, but then you set it again (replacing it). So you only get the last.
You must add each choice to a List and then question.setChoices(choices)
where choices
is a List . (When you get a "choice" you do choices.add(xmlInnetText.toString().trim());
Edit: also as @rmlan said it doesn't seem you would ever get to "choice". You don't need to do an if
inside the "choices" if
. The "choice" if
can be at the same level as the others if
s. Aside this fact the answer above true: you need a List to save each "choice".
Edit2:
You need something like this:
(...)
} else if(localName.equals("choice")) {
choices.add(setChoice(xmlInnerText.toString().trim());
} else if(localName.equals("choices")){
question.setChoices(choices);
}
(...)
Upvotes: 1