天天看點

[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]适用于UWP的XmlDocument使用方法

unity3D 中的XmlDocument.Load:

[Unity3D]适用于UWP的XmlDocument使用方法

是以在實際程式設計中,最好隻使用兩者都支援的方法。

下面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(), GUILayout.MinHeight()))
        {
            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(), GUILayout.MinHeight()))
        {
            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();
    }
}
           

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

[Unity3D]适用于UWP的XmlDocument使用方法

繼續閱讀