Hello all,
I’m currently trying to load data from an XML file and i can’t figure out how to set the xml path to be loaded right.
I have a couple of classes which are set like this:
Question.cs
public class Question
{
[XmlAttribute("Type")]
public string type;
[XmlElement("Question")]
public string question;
}
QuestionContainer.cs
[XmlRoot("QuestionCollection")]
public class QuestionContainer
{
[XmlArray("Questions")]
[XmlArrayItem("Question")]
public List<Question> questions = new List<Question>();
public static QuestionContainer Load(string path)
{
TextAsset _xml = Resources.Load<TextAsset>(path);
//TextAsset _xml = Resources.Load<TextAsset>(fileName).text;
XmlSerializer serializer = new XmlSerializer(typeof(QuestionContainer));
StringReader reader = new StringReader(_xml.text);
QuestionContainer questions = serializer.Deserialize(reader) as QuestionContainer;
reader.Close();
return questions;
}
}
XML File which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<QuestionCollection>
<Questions>
<Question type="Type1">
<Question>Q1</Question>
</Question>
<Question type="Type2">
<Question>Q2</Question>
</Question>
</Questions>
</QuestionCollection>
I’m trying to load the XML file like this:
public const string path = "Assets/questionsList.xml";
// Start is called before the first frame update
void Start()
{
QuestionContainer qc = QuestionContainer.Load(path);
foreach (Question question in qc.questions)
{
print(question.type);
}
}
However this does not work, i’ve tried to switch a couple of times the “path” variable and even tried to get the path of the TextAsset, however this does not seem that straight forward.
How could i load this file into my function?