您的位置:首页 > 数据库

XML读取的几种方式

2018-01-02 17:34 204 查看
编写一个XML文件如下:

[html] view plain copy print?<?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>
<?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数组,数组包括了这个节点的所有内容

代码如何:

[csharp] view plain copy print?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);
}

}

}
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查找所有目标名称的子节点

代码如下:

[csharp] view plain copy print?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);
}
}
}
}

}
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);
}
}
}
}

}


输出后结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库