this post shows a simple 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 it with Resources class from Unity3D
xml sample:
<achievement>
<uniqueid>0</uniqueid>
<referencename>My Achievement</referencename>
<goal>Solve until 10 seconds</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);
}
}
How to read?
Pretty simple! Use .NET framework, XmlDocument will 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 multiple hierarchies you will must implement your own ReadMethod to do that by navigating 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! :)