【Unity3D自学记录】解析XML的几种方式

编写一个XML文件如下:

<?xml version="1.0" encoding="utf-8"?>
<Xml>
	<JD>
		<Name>节点01</Name>
		<X>001</X>
		<Y>002</Y>
	</JD>
	<JD>
		<Name>节点02</Name>
		<X>003</X>
		<Y>004</Y>
	</JD>
	<JD>
		<Name>节点03</Name>
		<X>005</X>
		<Y>006</Y>
	</JD>
</Xml>

接下来Unity中写代码

第一种方式

通过GetElementsByTagName直接获取节点,返回类型是XmlNodeList数组,数组包括了这个节点的所有内容

代码如何:

using UnityEngine;
using System.Collections;
using System.Xml;

public class DJH_Read : MonoBehavIoUr {

	// Use this for initialization
	void Start () {
        string url = Application.dataPath + "/MyTest.xml";
        XmlDocument XmlDoc=new XmlDocument();
        XmlDoc.Load(url);

        int XmlCount = XmlDoc.GetElementsByTagName("JD")[0].ChildNodes.Count;

        for (int i = 0; i < XmlCount; i++)
        {
            string NameValue = XmlDoc.GetElementsByTagName("JD")[0].ChildNodes[i].InnerText;
            Debug.Log(NameValue);
        }

    }

}

输出后结果:



第二种方式

通过foreach查找所有目标名称的子节点

代码如下:

using UnityEngine;
using System.Collections;
using System.Xml;

public class DJH_Read : MonoBehavIoUr {

	// Use this for initialization
	void Start () {
        string url = Application.dataPath + "/MyTest.xml";
        XmlDocument XmlDoc=new XmlDocument();
        XmlDoc.Load(url);

        XmlNodeList nodeList = XmlDoc.SelectSingleNode("Xml").ChildNodes;
        foreach (XmlElement xe in nodeList)
        {
            foreach (XmlElement xxe in xe.ChildNodes)
            {
                if (xxe.Name == "Name")
                {
                    Debug.Log(xxe.InnerText);
                }
            }
        }
    }

}

输出后结果:

相关文章

前言 本文记录unity3D开发环境的搭建 unity安装 unity有中文...
前言 有时候我们希望公告牌跟随镜头旋转永远平行面向屏幕,同...
前言 经过一段时间的学习与实际开发,unity3D也勉强算是强行...
前言 在unity中我们常用的获取鼠标点击的方法有: 1、在3D场...
前言 在之前的例子中,我们都没有用到unity的精髓,例如地形...
这篇文章将为大家详细讲解有关Unity3D中如何通过Animator动画...