加载简单的XML文件无法正常工作,教育游戏

时间:2015-10-30 17:58:12

标签: xml unity3d xml-parsing

大家好,我可能会帮助我。制作简单的教育测验型游戏,我最后一步卡住了>我无法从XML文件加载数据。 这是一个xml文件的例子。

CREATE TABLE ts2 LIKE ts1;
INSERT INTO ts2 SELECT DISTINCT * FROM ts1;

这应该加载XML数据

<QuestionData>
<Question>
<questionText>4+4?</questionText>
<answerA>1</answerA>
<answerB>2</answerB>
<answerC>8</answerC>
 <answerD>4</answerD>
<correctAnswer>8</correctAnswer>
 </Question>
 <Question> 
   .......(another question+answers)
 </Question>
  </QuestionData>

现在,这是我将数据附加到特定游戏对象的脚本。但是,加载xml数据似乎根本不起作用。

using UnityEngine;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System;

public struct Question {
public string questionText;
public string answerA;
public string answerB;
public string answerC;
public string answerD;
public string correctAnswerID; 
}

[XmlRoot]

public class QuestionData {
[XmlArray("questions")]
[XmlArrayItem("Question")]
public List<Question> questions = new List<Question>();

public static QuestionData LoadFromText(string text) {
    try {
        XmlSerializer serializer = new XmlSerializer(typeof(QuestionData));            
        return serializer.Deserialize(new StringReader(text)) as QuestionData;
    } catch (Exception e) {
        UnityEngine.Debug.LogError(e);
        return null;
    }
}
}

当我调试questionData.questions.Count和currentQuestion时,我总是得到0值。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

尝试将xml对象更改为具有xml属性声明的类。此外,我没有看到您将currentQuestion分配给任何内容。

[XmlRoot(ElementName = "Question")]
public class Question
{
    [XmlElement(ElementName = "questionText")]
    public string QuestionText { get; set; }
    [XmlElement(ElementName = "answerA")]
    public string AnswerA { get; set; }
    [XmlElement(ElementName = "answerB")]
    public string AnswerB { get; set; }
    [XmlElement(ElementName = "answerC")]
    public string AnswerC { get; set; }
    [XmlElement(ElementName = "answerD")]
    public string AnswerD { get; set; }
    [XmlElement(ElementName = "correctAnswer")]
    public string CorrectAnswer { get; set; }
}

[XmlRoot(ElementName = "QuestionData")]
public class QuestionData
{
    [XmlElement(ElementName = "Question")]
    public List<Question> Question { get; set; }

    static public QuestionData LoadFromText(string text)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(QuestionData));
            return serializer.Deserialize(new StringReader(text)) as QuestionData;
        }
        catch (Exception e)
        {
            UnityEngine.Debug.LogError(e);
            return null;
        }
    }
}