实现unity下加载xml文件。
a. 准备1个文本格式为utf-8的xml文件,以及读取文件的LoadXMLFile.cs脚本;
b. LoadXMLFile脚本代码如下:
usingUnityEngine;
using System.Collections;
usingSystem.IO;
usingSystem.Xml;
publicclass LoadXMLFile : MonoBehaviour {
//存放xml中需要获取的内容
private string[] _xmlStr;
void Start()
{
LoadXML();
//将xml中需要显示的内容显示出来
if(_xmlStr != null && _xmlStr.Length> 0)
{
foreach(string str in _xmlStr)
{
Debug.Log(str);
}
}
}
private void LoadXML()
{
//设置文件位置,根据自己的需要进行设置
string filePath = Application.dataPath+ "/LoadFileStudy/Resources/studyXML.xml";
try
{
XmlDocument xmlDoc = newXmlDocument();
xmlDoc.Load(filePath);
XmlNodeList node =xmlDoc.SelectSingleNode("root").ChildNodes;
foreach(XmlElement nodeList innode)
{
foreach (XmlElement xe innodeList)
{
//设置标签为“array”的元素为显示内容,获取并赋值给_xmlStr
if(xe.Name =="array")
{
int i = 0;
_xmlStr = newstring[xe.ChildNodes.Count];
foreach(XmlElement xe1in xe)
{
_xmlStr[i] =xe1.InnerText;
i++;
}
break;
}
}
}
}
catch (IOException e)
{
Debug.Log("加载出现问题,问题描述:"+ e);
}
}
}
c. 将LoadXMLFile脚本组件添加至摄像机后,运行可看到Console输出如图1所示:
图1
d. studyXML中内容如图2所示:
图2