您的位置:首页 > 其它

使用WWW获取本地文件夹的XML配置文件

2014-12-15 10:11 375 查看
Unity3D读取本地文件可以使用Resources.Load来读取放在Resources文件夹下的文件,如果不是放在该文件夹下,则可以通过WWW类来读取。

譬如读取xml的配置文件。

/// <summary>
/// 读取颜色配置
/// </summary>
/// <returns></returns>
public List<Color> GetColorXml()
{
string xmlPath = Application.dataPath + @"/Configs/Config.xml";
List<Color> colorList = new List<Color>();
if (File.Exists(xmlPath))
{
XmlDocument xmlDoc = new XmlDocument();
WWW www = new WWW("file:// " + xmlPath);
while (true)
{
if (www.isDone)
{
System.IO.StringReader stringReader = new System.IO.StringReader(www.text);
stringReader.Read(); // skip BOM
xmlDoc.LoadXml(stringReader.ReadToEnd());
//xmlDoc.LoadXml(www.text);
break;
}
}

//xmlDoc.Load(xmlPath);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Config/ColorConfig").ChildNodes;

//遍历每一个节点,拿节点的属性以及节点的内容
foreach (XmlElement xe in nodeList)
{
//Debug.Log("Attribute :" + xe.GetAttribute("id"));
//Debug.Log("NAME :" + xe.Name);
if (xe.Name != "Color")
{
continue;
}

Color c1 = new Color();
foreach (XmlElement x1 in xe.ChildNodes)
{
if (x1.Name == "r")
{
float.TryParse(x1.InnerText, out c1.r);
c1.r = c1.r > 1f ? c1.r / 255f : c1.r;
}
if (x1.Name == "g")
{
float.TryParse(x1.InnerText, out c1.g);
c1.g = c1.g > 1f ? c1.g / 255f : c1.g;
}
if (x1.Name == "b")
{
float.TryParse(x1.InnerText, out c1.b);
c1.b = c1.b > 1f ? c1.b / 255f : c1.b;
}
if (x1.Name == "a")
{
float.TryParse(x1.InnerText, out c1.a);
c1.a = c1.a > 1f ? c1.a / 255f : c1.a;
}
}
colorList.Add(c1);
}

}
return colorList;

}


如果读取的xml文件有问题,可能是编码格式引起的,可以使用StringReader来读取代替www.text

xml相关问题参考:http://answers.unity3d.com/questions/10904/xmlexception-text-node-canot-appear-in-this-state.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: