PDA

View Full Version : Help reading XML content via Actionscript


Captain Education
06-17-2008, 06:17 PM
I am trying to populate a quiz using XML data instead of just hard-coding the content within Flash. The XML structure I will be using looks like this:

<?xml version="1.0"?>
<Question id='Q1'>>
<QuestionType>TrueFalse</QuestionType>
<Title>XML is difficult</Title>
<Answer>false</Answer>
<Points>100</Points>
</Question>


<Question id='Q2'>
<QuestionType>MultipleChoice</QuestionType>
<Title>What is the best day of the week?</Title>
<potentialAnswer_a>Monday</potentialAnswer_a>
<potentialAnswer_b>Wednesday (hump day)</potentialAnswer_b>
<potentialAnswer_c>Friday</potentialAnswer_c>
<potentialAnswer_d>Saturday</potentialAnswer_d>
<Answer>d</Answer>
<Points>200</Points>
</Question>

There could be 50+ questions when all is said and done, so this must be scalable. I have had some luck creating an XML object, then accesing the various nodes with code like:

myQuizContent = new XML();
myQuizContent.ignoreWhite = true;

myQuizContent.onLoad = function (success)
{
if (success)
{
parseXML();
}
}
myQuizContent.load("quizQuestions.xml");

function parseXML()
{
QuestionContent = new XML();
QuestionContent.parseXML(myQuizContent);

// Q1 content
_global.Q1questionType = QuestionContent.idMap['Q1'].firstChild.nextSibling.firstChild;
_global.Q1questionTitle = QuestionContent.idMap['Q1'].firstChild.nextSibling.nextSibling.firstChild;
_global.Q1correctAnswer = QuestionContent.idMap['Q1'].firstChild.nextSibling.nextSibling.nextSibling.fi rstChild;

trace ("the question type for Q1 is:"+_global.Q1questionType);
trace ("the question TITLE for Q1 is:"+_global.Q1questionTitle);
trace ("the correct answer for Q1 is:"+_global.Q1correctAnswer);


// Q2 content
_global.Q2questionType = QuestionContent.idMap['Q2'].firstChild.firstChild;
_global.Q2questionTitle = QuestionContent.idMap['Q2'].firstChild.nextSibling.firstChild;
_global.Q2correctAnswer = QuestionContent.idMap['Q2'].firstChild.nextSibling.nextSibling.nextSibling.ne xtSibling.nextSibling.nextSibling.firstChild;

trace ("the question type for Q2 is:"+_global.Q2questionType);
trace ("the question TITLE for Q2 is:"+_global.Q2questionTitle);
trace ("the correct answer for Q2 is:"+_global.Q2correctAnswer);
//trace ("the question type for Q2 is:"+QuestionContent.idMap['Q2'].firstChild.firstChild);
//trace ("the question type for Q3 is:"+QuestionContent.idMap['Q3'].firstChild.firstChild);
}

I was able to hack around with this until I got the desired results (confirmed with the trace output), but I must be doing this the wrong way.

So this is my burning question! Do I HAVE to reference the XML content using firstChild.nextSibling.firstChild (etc, etc)? Since I took the time to logically name the nodes, why can't I reference them like this?

QuestionContent.idMap['Q2'].Title

Or can I? Any assistance would be greatly appreciated...