Unity、C#读取XML

有如下XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<DataNode>
  <province id ="01" name="江苏"><!--省-->
    <city id ="01" name ="南京"></city><!--城市-->
    <city id ="02" name ="镇江"></city>
    <city id ="03" name ="南通"></city>
  </province>
  <province id ="02" name="河南">
    <city id ="01" name ="郑州"></city>
    <city id ="02" name ="开封"></city>
    <city id ="03" name ="洛阳"></city>
  </province>
</DataNode>

那我们如何读取里面的信息,代码如下:

 1 using System.IO;
 2 using System.Xml;
 3 using UnityEngine;
 4 
 5 public class ReadXml : MonoBehaviour
 6 {
 7     private void Start()
 8     {
 9         string _path = Application.dataPath + "/TestXml.xml";
10         if (File.Exists(_path))
11         {
12             XmlDocument _xmlDoc = new XmlDocument();
13             //忽略XML中注释的影响。(默认情况下,读取xml文件是不忽略注释的,读取带注释的节点会造成异常,所以需要忽略注释的影响)
14             XmlReaderSettings _set = new XmlReaderSettings();
15             _set.IgnoreComments = true;
16             XmlReader _reader = XmlReader.Create(_path, _set);
17             //读取XML文件
18             _xmlDoc.Load(_reader);
19             //取根节点,根节点下的所有子节点(不包含孙节点)形成节点列表
20             XmlNodeList _nodeList = _xmlDoc.SelectSingleNode("DataNode").ChildNodes;
21             //遍历每一个节点,拿节点的属性以及节点的内容
22             foreach (XmlElement _xe in _nodeList)
23             {
24                 Debug.Log("节点名称:" + _xe.Name);
25                 Debug.Log("属性id :" + _xe.GetAttribute("id"));
26                 Debug.Log("属性name :" + _xe.GetAttribute("name"));
27                 foreach (XmlElement _x1 in _xe.ChildNodes)
28                 {
29                     if (_x1.Name == "city")
30                     {
31                         Debug.Log("city:" + _x1.InnerText);
32                     }
33                 }
34             }
35             //打印XML字符串
36             Debug.Log("all = " + _xmlDoc.OuterXml);
37         }
38     }
39 }

其实XML的读取很简单,引用 System.Xml 类库,利用里面的一些方法一层层遍历节点就可以取到自己想要的值。

猜你喜欢

转载自www.cnblogs.com/xiaoyulong/p/9384947.html