using System.Collections;
using System.Xml;
using System.IO;
public class ReadXml : MonoBehaviour {
private string[] myNames;
// Use this for initialization
void Start () {
LoadMyXML();
}
// Update is called once per frame
void Update () {
}
private void LoadMyXML()
{
//xml存放路径
string filePath = Application.dataPath + @"/testxml.xml";
Debug.Log ("filePath=" + filePath);
if (File.Exists(filePath))
{
//声明个xml文档
XmlDocument xmlDocument = new XmlDocument();
settings.IgnoreComments = true;//忽略文档里面的注释
//获取名称为myRoot的根节点
XmlNodeList xmlNodeList = xmlDocument.SelectSingleNode("myRoot").ChildNodes;
//Debug.Log(xmlNodeList.Count);
//遍历子节点
Debug.Log("readxml");
foreach (XmlElement xmlElement1 in xmlNodeList)
{
if (xmlElement1.Name == "myChild")
{
int index = 0;
myNames = new string[xmlElement1.ChildNodes.Count];
//Debug.Log(xmlElement1.ChildNodes.Count);
foreach (XmlElement xmlElement2 in xmlElement1.ChildNodes)
{
myNames[index] = xmlElement2.InnerText;
Debug.Log(myNames[index]);
index++;
}
}
}
}
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<myRoot>
<myChild>
<myName>张三</myName>
<myName>李四</myName>
<myName>王老五</myName>
<myName>刘邦</myName>
<myName>项羽</myName>
<myName>秦始皇</myName>
<!--记录书本的信息-->
</myChild>
</myRoot>
xml文件保存路径
string filePath;
#if UNITY_STANDALONE_WIN && UNITY_EDITOR
filePath=Application.dataPath + @"/UserMessageXml.xml";
#elif UNITY_IOS && UNITY_ANDROID
filePath=Application.persistentDataPath+"/UserMessageXml.xml";
#endif
Debug.Log ("path=" + filePath);
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("transforms");
xmlDoc.AppendChild(root);
xmlDoc.Save(filepath);
移动端需要一开始就创建一个xml,不能保存到Resource中的xml文件。
xml文件读取路径
//从Resource中加载; 一般用于移动端
TextAsset t = Resources.Load("Init") as TextAsset ;
xmlDocument.Load(XmlReader.Create(new StringReader(t.text),settings));
//从发布文件中的XXXXX_Data中读取,需要手动添加xml文件 一般用于PC
filePath=Application.dataPath+"/Init1.xml";
xmlDocument.Load(XmlReader.Create(filePath,settings));