[Unity3D]適用於UWP的XmlDocument使用方法

上一篇講了在Unity3D中UWP可以使用的XML的序列化的方法。
上文鏈接:[Unity3D]在UWP工程中使用的序列化方法
但是XmlReader和XmlWriter使用起來很麻煩,所以本篇演示XmlDocument既可在UWP中使用又可在Unity3D編輯器中使用的方法。

UWP和Unity3D都支持XmlDocument類,但由於程序集的不同,有些在Unity3D中可以用的方法在UWP中無法使用,最終導致在編譯UWP工程時失敗。比如XmlDocument.Load方法在UWP中就沒有通過文件路徑調用的重載。

uwp 中的XmlDocument.Load:
這裏寫圖片描述

unity3D 中的XmlDocument.Load:
這裏寫圖片描述

所以在實際編程中,最好只使用兩者都支持的方法。

下面UWP和Unity3D都支持的使用方法:

using UnityEngine;
using System.Xml;
using System.Text;

//利用宏定義區分Unity3D與UWP的引用空間
#if NETFX_CORE
using Windows.Storage;
using System.IO;
using XmlReader = WinRTLegacy.Xml.XmlReader;
using XmlWriter = WinRTLegacy.Xml.XmlWriter;
using StreamWriter = WinRTLegacy.IO.StreamWriter;
using StreamReader = WinRTLegacy.IO.StreamReader;
#else
using XmlReader = System.Xml.XmlReader;
using XmlWriter = System.Xml.XmlWriter;
using StreamWriter = System.IO.StreamWriter;
using StreamReader = System.IO.StreamReader;
#endif

public class test : MonoBehaviour
{
    string outMsg = "請先寫入一遍文件再讀取。\n";

    //利用遞歸的方式,輸出元素
    void ShowXml(XmlNode rootNode)
    {
        if (null == rootNode)
        {
            return;
        }

        if (XmlNodeType.Element == rootNode.NodeType)
        {
            outMsg += "<" + rootNode.Name + ">";
            foreach (XmlNode node in rootNode.ChildNodes)
            {//繼續遍歷子節點
                ShowXml(node);
            }
            outMsg += "</" + rootNode.Name + ">";
        }
        else if (XmlNodeType.Text == rootNode.NodeType)
        {
            outMsg += rootNode.InnerText;
        }
    }

    void OnGUI()
    {
        GUILayout.BeginHorizontal();
        GUILayout.BeginVertical();

        //讀取
        if (GUILayout.Button("Read", GUILayout.MinWidth(120), GUILayout.MinHeight(80)))
        {
            try
            {
                XmlDocument doc = new XmlDocument();

#if NETFX_CORE
                var asyncOpt = ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("UserInfo");
                asyncOpt.Wait();
                using (var fileStream = asyncOpt.Result)
#else
                using (var fileStream = new StreamReader(Application.streamingAssetsPath + "/UserInfo", Encoding.UTF8))
#endif
                {
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.IgnoreComments = true;//讀取時忽略註釋
                    using (var reader = XmlReader.Create(fileStream, settings))
                    {
                        //加載Xml文件
                        doc.Load(reader);
                    }

                    //顯示Xml,也可直接調用doc.InnerText來獲取Xml字符串
                    ShowXml(doc.LastChild);
                    outMsg += "\n";
                }
            }
            catch (System.Exception e)
            {
                outMsg += "Error >"+ e.Message +"\n";
            }
        }

        //寫入
        if (GUILayout.Button("Write", GUILayout.MinWidth(120), GUILayout.MinHeight(80)))
        {
            try
            {
                XmlDocument doc = new XmlDocument();

                //創建Root結點
                XmlNode rootNode = doc.CreateNode(XmlNodeType.Element, "Root", null);
                doc.AppendChild(rootNode);

                //爲根節點添加子節點Person1
                XmlNode personNode1 = doc.CreateNode(XmlNodeType.Element, "Person1", null);
                rootNode.AppendChild(personNode1);

                //爲Person1節點添加子節點
                XmlNode nameNode = doc.CreateNode(XmlNodeType.Element, "Name", null);
                nameNode.InnerText = "XiangMu";
                personNode1.AppendChild(nameNode);

                XmlNode oldNode = doc.CreateNode(XmlNodeType.Element, "Old", null);
                oldNode.InnerText = "11";
                personNode1.AppendChild(oldNode);

                XmlNode sexNode = doc.CreateNode(XmlNodeType.Element, "IsMan", null);
                sexNode.InnerText = "true";
                personNode1.AppendChild(sexNode);

                //爲Root節點添加Person2節點
                XmlNode personNode2 = doc.CreateNode(XmlNodeType.Element, "Person2", null);
                personNode2.InnerText = "Unknow";
                rootNode.AppendChild(personNode2);

#if NETFX_CORE
                var asyncWriteOpt = ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("UserInfo", CreationCollisionOption.ReplaceExisting);
                asyncWriteOpt.Wait();
                using (var fileStream = asyncWriteOpt.Result)
#else
                using (var fileStream = new StreamWriter(Application.streamingAssetsPath + "/UserInfo"))
#endif
                {
                    //保存修改或新建的Xml到文件流
                    doc.Save(fileStream);
                }
            }
            catch (System.Exception e)
            {
                outMsg += "Error >" + e.Message + "\n";
            }
        }

        GUILayout.EndVertical();

        GUILayout.TextArea(outMsg);

        GUILayout.EndHorizontal();
    }
}

學習不能一蹴而就,需要不斷積累與鞏固,才能得到提升。

這裏寫圖片描述

發佈了48 篇原創文章 · 獲贊 9 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章