- Home /
XML parsing problem - array
Hi guys,
I have to implement a quiz game and I'm trying to parse an XML file in order to retrieve all the contained data and use them to fill some buttons and labels with questions and answers.
This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<test nr="4">
<quiz quizNr="1">
<question>How are you?</question>
<answers totalNr="2">
<answer id="1" correct="true">Fine</answer>
<answer id="2" correct="false">bad</answer>
</answers>
</quiz>
<quiz quizNr="2">
<question>What is your name</question>
<answers totalNr="3">
<answer id="1" correct="true">Mark</answer>
<answer id="2" correct="false">John</answer>
<answer id="3" correct="false">Paul</answer>
</answers>
</quiz>
</test>
I'm able to parse it, but observing the inspector while running the simulation in the editor it seems that they are not stored correctly (that's a screencapture of my inspector).
I don't understand why Element1 and Element2 are empty and all the data about my second quiz are stored in Element3. Can someone help me in understanding what I did wrong?
This is my parser:
import System.Xml;
class Answer{
var answerID:int = 0;
var correct:String = " ";
var text:String = " ";
}
class Quiz{
var quizNr:int = 0;
var questionText:String;
var answerNr:int =0;
var answers:Answer[];
}
class Test{
var nr:int;
var quiz:Quiz[];
}
var test:Test;
function Start()
{
//readxml from chat.xml in project folder
var reader:XmlReader = XmlReader.Create("chat.xml");
reader.Read();
do
{
//when you find a quesiti tag do this
if(reader.IsStartElement("test"))
{
test.nr = parseInt(reader.GetAttribute("nr"));
test.quiz = new Quiz[test.nr];
for(var i:int = 0; i<test.nr; i++)
{
reader.Read();
if(reader.IsStartElement("quiz"))
{
test.quiz[i] = new Quiz();
test.quiz[i].quizNr=parseInt(reader.GetAttribute("quizNr"));
reader.Read();
if(reader.IsStartElement("question"))
{
test.quiz[i].questionText = reader.ReadString();
reader.Read();
if(reader.IsStartElement("answers"))
{
test.quiz[i].answerNr = parseInt(reader.GetAttribute("totalNr"));
test.quiz[i].answers = new Answer[test.quiz[i].answerNr];
for (var j:int = 0; j <test.quiz[i].answerNr; j++)
{
reader.Read();
if(reader.IsStartElement("answer"))
{
test.quiz[i].answers[j] = new Answer();
test.quiz[i].answers[j].answerID = parseInt(reader.GetAttribute("id"));
test.quiz[i].answers[j].correct = reader.GetAttribute("correct");
test.quiz[i].answers[j].text = reader.ReadString();
}
}
}
}
}
}
}
}while(reader.Read());
}
inspector.png
(17.7 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613084327im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
web page html parsing 1 Answer
XML File, or Array? 1 Answer
UnityScript XML parser 0 Answers
How can I turn XML to array? 0 Answers