NRE的编程笔记

导航

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             _reader.Close();
21             //取根节点,根节点下的所有子节点(不包含孙节点)形成节点列表
22             XmlNodeList _nodeList = _xmlDoc.SelectSingleNode("DataNode").ChildNodes;
23             //遍历每一个节点,拿节点的属性以及节点的内容
24             foreach (XmlElement _xe in _nodeList)
25             {
26                 Debug.Log("节点名称:" + _xe.Name);
27                 Debug.Log("属性id :" + _xe.GetAttribute("id"));
28                 Debug.Log("属性name :" + _xe.GetAttribute("name"));
29                 foreach (XmlElement _x1 in _xe.ChildNodes)
30                 {
31                     if (_x1.Name == "city")
32                     {
33                         Debug.Log("city:" + _x1.InnerText);
34                     }
35                 }
36             }
37             //打印XML字符串
38             Debug.Log("all = " + _xmlDoc.OuterXml);
39         }
40     }
41 }

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

posted on 2018-07-29 12:32  NRE  阅读(405)  评论(0编辑  收藏  举报