2014年8月28日 星期四

[Unity][C#]2 simple ways of load the data form XML // 兩種簡便讀取XML資料的方法

假如今天要讀取路徑為Resources/test.xml 的XML, 內容如下:
For example, the XML data we want read as below, the path is "Resources/test.xml":

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ROOT>
<table wave="1" level="1" name="aaa"/>
<table wave="2" level="1" name="bbb"/>
</ROOT>

我們有兩種簡便讀取的方法:
We have 2 simple ways can use:


1.Mono.XML

Mono.XML 可於Unity安裝目錄中搜尋到, 讀取範例:
You can get Mono.XML by seach the folder where Uniy install, the sample of XML read function as below:

using Mono.Xml;
using System.Security;

  void Read()
  {
    SecurityParser SP = new SecurityParser();
    string xmlPath = "test";

    SP.LoadXml(Resources.Load( xmlPath ).ToString());
    SecurityElement SE = SP.ToXml();
    foreach (SecurityElement child in SE.Children)
    {
      if(child.Tag == "table")
      {
        string xmlName = child.Attribute("name");
        Debug.Log("Name=" + xmlName);
      }
    }
  }


2.XMLPaser

如果你想輸出Windows phone 8的專案, 你會發現它不支援SecurityElement, 因此必須使用System.xml, 而XMLPaser即支援此種作法
If you want to build the project for theWindows phone 8, you'll find that it doesn't support SecurityElement.
So we have to use System.xml, and XMLPaser support it.


XMLPaser官方載點: http://dev.grumpyferret.com/unity/
The official XMLPaser download page: http://dev.grumpyferret.com/unity/

不過我自己稍微改寫了一下, 讓XMLPaser可以判斷Tab字元\t, 這樣有助於XML的排版
載點:http://goo.gl/YDg4pW
But I modify someting, for determine the Tab char "\t", it helps XML typesetting.
Download:http://goo.gl/YDg4pW

讀取範例:
The sample of the function:

using System.Xml;
  void Read()
  {
    TextAsset xmlData ;
    XMLParser xmlPaser;
    XMLNode xmlNode;

    xmlData = (TextAsset)Resources.Load ("test", typeof(TextAsset));
    xmlPaser = new XMLParser ();
    xmlNode = xmlPaser.Parse (xmlData.text);

    int listCount = xmlNode.GetNodeList ("ROOT>0>table").Count;

    for(int i =0; i < listCount ; i++){
      string xmlName= xmlNode .GetValue("ROOT>0>table>"+i+">@name");
      Debug.Log("Name=" + xmlName);
    }
  }


沒有留言:

張貼留言