目录
一、目的
1、想知道:Unity怎么读取xml文件:pc端
二、参考:
1、Unity安卓配置文件:读和写
https://blog.csdn.net/qq_40544338/article/details/102570247
- 总结:good:读写功能都有。
1、Unity3D_08_XML文件创建,读取,修改,添加
https://www.cnblogs.com/NBOWeb/p/8968036.html
- 总结:good
三、操作:一:完成:读取已经写好的xml文件
1、新建xml文件
①将其放到指定文件夹中,文件夹位置在后面代码中是可以修改的
<item>
<item1>
<id>1</id>
<name>china</name>
<year>2016</year>
</item1>
<item2>
<id>2</id>
<name>usa</name>
<year>2017</year>
</item2>
</item>
1、Unity添加代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;
//按键操作物体移动
public class _move : MonoBehaviour
{
private string name1;
private string name2;
private string year1;
private string year2;
private string id1;
private int id2;
void Start()
{
parseXml();
}
//解析xml
void parseXml()
{
//也可以前面加上@,区别就是有@的话,双引号里面的内容不转义,比如" \" "
//string filePath = Application.dataPath+@"/Resources/item.xml";
string filePath = Application.dataPath + "/Resources/item.xml";
if (File.Exists(filePath))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlNodeList node = xmlDoc.SelectSingleNode("item").ChildNodes;
//遍历节点
foreach (XmlElement ele in node)
{
//item下面的节点
Debug.Log(ele.Name);
if (ele.Name == "item1")
{
//first item1
foreach (XmlElement i1 in ele.ChildNodes)
{
Debug.Log(i1.Name);
if (i1.Name == "id")
{
id1 = i1.InnerText;
}
if (i1.Name == "name")
{
name1 = i1.InnerText;
}
if (i1.Name == "year")
{
year1 = i1.InnerText;
}
}
}
if (ele.Name == "item2")
{
//first item1
foreach (XmlElement i2 in ele.ChildNodes)
{
Debug.Log(i2.Name);
if (i2.Name == "id")
{
id2 =int.Parse(i2.InnerText);
}
if (i2.Name == "name")
{
name2 = i2.InnerText;
}
if (i2.Name == "year")
{
year2 = i2.InnerText;
}
}
}
}
}
Debug.Log("id1: " + id1);
Debug.Log("name1: " + name1);
Debug.Log("year1: " + year1);
Debug.Log("id2: " + id2);
Debug.Log("name2: " + name2);
Debug.Log("year2: " + year2);
}
}
1、注意
①使用装换将string转换为int类型,配置文件中的string类型无法转换,只能是配置文件中就是int的类型
id2 =int.Parse(i2.InnerText);