2016. 2. 22. 05:30

this post shows asimple tutorial to do some basic operations with xml file on Unity3D using C#.

How to load?

Put an XML file on Resources folder and load itwith Resources class from Unity3D
xml sample:

<achievement>

 <uniqueid>0</uniqueid>

 <referencename>MyAchievement</referencename>

 <goal>Solve until 10seconds</goal>

 <points>10</points>

</achievement>

 

using UnityEngine;

using System.Collections;

using System.Xml;

 

 

public class XMLEditor : MonoBehaviour

{

 

   void Awake()

    {

       //Load

       TextAsset textXML = (TextAsset)Resources.Load("myxml.xml",typeof(TextAsset));

       XmlDocument xml = new XmlDocument();

       xml.LoadXml(textXML.text);

    }

}

Yeah! Using a TextAsset you can make it very simply!

How to read?

Pretty simple! Use .NET framework, XmlDocumentwill turn you live more easy.

using UnityEngine;

using System.Collections;

using System.Xml;

 

 

public class XMLEditor : MonoBehaviour

{

   void Awake()

    {

       //Load

       TextAsset textXML = (TextAsset)Resources.Load("myxml.xml",typeof(TextAsset));

       XmlDocument xml = new XmlDocument();

       xml.LoadXml(textXML.text);

 

       //Read

       XmlNode root = xml.FirstChild;

       foreach(XmlNode node in root.ChildNodes)

       {

           if (node.FirstChild.NodeType == XmlNodeType.Text)

                Debug.Log(node.InnerText);

       }

    }

}


Ok, but if there are multiplehierarchies you will must implement your own ReadMethod to do that bynavigating for all nodes.

How to save?

using UnityEngine;

using System.Collections;

using System.Xml;

 

 

public class XMLEditor : MonoBehaviour

{

   void Awake()

    {

       //Load

       TextAsset textXML = (TextAsset)Resources.Load("myxml.xml",typeof(TextAsset));

       XmlDocument xml = new XmlDocument();

       xml.LoadXml(textXML.text);

 

       //Read

       XmlNode root = xml.FirstChild;

        foreach(XmlNode node in root.ChildNodes)

       {

           if (node.FirstChild.NodeType == XmlNodeType.Text)

                node.InnerText ="none";

       }

 

       //Simple Save

       xml.Save(AssetDatabase.GetAssetPath(textXML));

    }

}

The easy way! :)



출처 : http://fernandogamedev-en.blogspot.kr/2012/09/how-to-load-read-and-save-xml-on-unity3d.html

Posted by 시리시안