Unity怎么读取XML配置文件 C#解析XML数据

推荐使用System.Xml.Linq(LINQ to XML)读取XML配置文件,将config.xml放入Assets/Resources/Configs/并用Resources.Load("Configs/config")获取TextAsset,再通过XDocument.Parse(textAsset.text)解析;也可用XmlSerializer反序列化为强类型对象,需注意UTF-8无BOM编码、平台兼容性及缓存优化。

Unity中读取XML配置文件,推荐用C#原生的System.Xml或更现代的System.Xml.Linq(即LINQ to XML)。前者兼容性好,后者语法简洁、易读易写,适合大多数项目。

把XML文件放进Resources文件夹(最简单方式)

Unity不支持直接用File.ReadAllText读取任意路径的XML(尤其在WebGL或移动端),所以建议把配置文件放在Assets/Resources/下,用Resources.Load加载:

  • config.xml放入Assets/Resources/Configs/(路径可自定义)
  • 确保文件扩展名是.xml,且Unity未将其识别为文本资源以外的类型(可在Inspector里确认Text Asset类型)
  • 代码中用Resources.Load("Configs/config")获取——注意不用写.xml后缀

用XDocument解析XML(推荐LINQ to XML)

XDocumentXmlDocument更轻量、API更直观。加载完TextAsset后,用其text属性创建XDocument:

XDocument doc = XDocument.Parse(textAsset.text);
var root = doc.Root;
// 例如读取 
double volume = (double)root.Attribute("volume");
bool fullscreen = (bool)root.Attribute("fullscreen");
// 读取子节点:
var level = root.Element("Level");
string levelName = level?.Attribute("name")?.Value;
string difficulty = level?.Attribute("difficulty")?.Value;

用XmlSerializer反序列化成对象(适合结构固定场景)

如果XML格式规范、和C#类一一对应,可用XmlSerializer自动映射。先定义带[XmlRoot][XmlElement]等特性的类:

[XmlRoot("GameSettings")]
public class GameConfig
{
    [XmlAttribute] public float volume;
    [XmlAttribute] public bool fullscreen;
    [XmlElement("Level")] public List levels;
}

public class LevelData
{
    [XmlAttribute] public string name;
    [XmlAttribute] public string difficulty;
}

// 使用:
var serializer = new XmlSerializer(typeof(GameConfig));
using var reader = new StringReader(textAsset.text);
GameConfig config = (GameConfig)serializer.Deserialize(reader);

注意:XmlSerializer要求类为public,字段/属性有public get/set,且不能有无参构造函数缺失等问题。

注意事项和常见坑

Unity Editor里测试正常,但打包后可能出错,主要因路径或编码问题:

  • XML文件保存时用UTF-8无BOM格式(VS Code或Notepad++可设置),避免中文乱码
  • WebGL平台不支持Resources.Load异步加载XML?实际支持,但必须确保构建时勾选了Include Text Assets(默认已包含)
  • Android/iOS上Application.streamingAssetsPath也可放XML,但需用WWWUnityWebRequest异步读取,不能直接File.Read
  • 频繁读取?缓存解析结果,不要每帧都Parse