I want to make a template for questionnaires in Flex 3, that reads dynamic XML file and creates a questionnaire. An exemplary XML:
<test>
<question>
<q>Who was born earlier?</q>
<answer value="true">Vincent van Gogh</answer>
<answer value="false">Piet Mondrian</answer>
</question>
<question>
<q>What color is Dutch national flag?</q>
<answer value="false">blue, red and green</answer>
<answer value="false">green, red and white</answer>
<answer value="true">blue, red and white</answer>
<开发者_JAVA技巧;/question>
<question>
<q>Which season is the coldest?</q>
<answer value="false">fall</answer>
<answer value="true">winter</answer>
<answer value="false">spring</answer>
<answer value="false">summer</answer>
</question>
</test>
The amount of questions and answers may vary. The plan was to use nested repeaters with radio buttons (one for the questions and then another inside for the answers). I can save all question.q to an ArrayCollection, but how should I handle my answers, if there are few of them with the same "answer" tag within each question? And how can I access "value" property of each, to check if the user chose correct answer?
You need to create a domain model from the XML. Don't skip this step because it's easy to do and more straightforward than you think. Start by creating a simple class:
public class Question {
public var question : String;
public var answers : ArrayCollection = new ArrayCollection();
public Question( node : XML ) {
question = node.q.text();
for each( var answer : XML in question.answer ) {
answers.addItem( new Answer( answer ) );
}
}
}
public class Answer {
public var text : String;
public var correct : Boolean;
public Answer( node : XML ) {
text = node.text();
correct = Boolean(node.@value);
}
}
Populate an ArrayCollection of your nodes like so:
var questions = new ArrayCollection();
for each( var node : XML in xml.question ) {
questions.addItem( new Question( node ) );
}
That's roughly it. Then your questions array can serve as the dataProvider for the repeater. And question.answers can serve as the repeater for the inner repeater.
精彩评论