unity c#读取xml

本文介绍如何使用C#语言解析XML文件,并通过代码示例详细解释了如何读取XML文件中的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using UnityEngine;
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();


XmlReaderSettings settings = new XmlReaderSettings();

settings.IgnoreComments = true;//忽略文档里面的注释


xmlDocument.Load(XmlReader.Create(filePath,settings));


//获取名称为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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值