我在解析XML文件到C#中的对象时遇到了一些问题。整个项目在Unity3D中。所以我有这个XML文件:在Unity C中解析XML文件#
<Questions>
<Question>
<questionText>What is this?</questionText>
<answer>blablabla</answer>
</Question>
</Questions>
这是我的解析类:
using UnityEngine;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System;
public struct Montage {
[XmlElement("questionText")]
public string questionText;
[XmlElement("answer")]
public string answer;
}
[XmlRoot("Questions"), XmlType("Questions")]
public class ConfigScene {
[XmlArray("Questions")]
[XmlArrayItem("Question")]
public List<Montage> questions = new List<Montage>();
public static ConfigScene Load(string path) {
try {
XmlSerializer serializer = new XmlSerializer (typeof(ConfigScene));
using(FileStream stream = new FileStream(path, FileMode.Open)) {
return serializer.Deserialize(stream) as ConfigScene;
}
} catch (Exception e) {
UnityEngine.Debug.LogError ("Exception loading config file: " + e);
return null;
}
}
}
我打电话相机对象本 “装载” 方法开始()方法:
void Start() {
confScene = ConfigScene.Load(Path.Combine(Application.dataPath, "Config/config2.xml"));
foreach(Montage o in confScene.questions) {
Debug.Log (o.questionText);
}
}
问题是我的问题列表是空的,我没有得到任何提供的数据。我做错了什么?也许有人以前做过,并知道这段代码有什么问题?
首先确保您的文件路径正常。这就是文件__config2.xml__存在于路径Application.dataPath +“Config /”中。你可以在方法'Start()'012h中打印路径。其次确保你没有在方法'Load()'中得到异常。异常不会从那里重新抛出。您应该检查Unity应用程序日志。 –
正如我看到的路径是好的,但当我记录整个路径组合,我得到这样的东西:“F:/ Unity项目/蒙太奇游戏/资产\配置/ config2.xml”。正如你看到的斜线之一是反斜杠(Config之前)。这是一个错误还是什么? – Celdur
这条路显然是错的。你不能混淆向前和向后的斜杠。如果你在Windows上,所有的应该是反斜杠,而在基于Unix的系统上则应该是反斜杠。现在,您可以手动连接路径来检查,而不是使用'Path.Combine()'。什么是您的操作系统,BTW? –