After getting a bit of an answer from here: Converting from system.xml to mono.xml - Questions & Answers - Unity Discussions
I decided to try and use the suggested TinyXML class to read my data. However, i cannot get to information that is stored deep within tags. For example, i want to get the content from the second of three “string” tags that are all stored inside a “dict” tag which is stored inside another “dict” tag. If it cannot be done with TinyXML then i am happy to change to any other suggestion.
Try this xmltest.cs
. This kinda shows how to use mono.xml
. I’ve not used this code in production, but it compiles, and dumps out the expected values to the console. You’ll need to grab the mono.xml
zip file linked to from the Unity website, and copy the files into your project.
//c#
using UnityEngine;
using System.Collections;
using Mono.Xml;
using System.IO;
public class xmltest : MonoBehaviour {
class Handler : SmallXmlParser.IContentHandler {
public void OnStartParsing (SmallXmlParser parser)
{ // start of file
}
public void OnEndParsing (SmallXmlParser parser)
{ // end of file
}
public void OnStartElement (string name, SmallXmlParser.IAttrList attrs)
{ // opening tag, with attributes
Debug.Log ("Got <" + name + ">");
foreach (string s in attrs.Names)
Debug.Log ("Attribute name: " + s);
foreach (string t in attrs.Values)
Debug.Log ("Attribute value: " + t);
}
public void OnEndElement (string name)
{ // closing tag
}
public void OnChars (string s)
{ // string between open and closing tag
Debug.Log (s);
}
public void OnIgnorableWhitespace (string s)
{
}
public void OnProcessingInstruction (string name, string text)
{
}
}
void Start () {
SmallXmlParser x = new SmallXmlParser();
Handler h = new Handler();
TextReader textReader = new StreamReader(Application.dataPath + "/test.xml");
x.Parse(textReader, h);
}
}
I tested this code with the following in Assets/test.xml
.
<?xml version="1.0"?>
<dict>
<dict>
<string jim="sheila">fred</string>
<string>Douglas</string>
<string>Another string</string>
</dict>
</dict>
Note that there is no way to say “get me the second string two dicts down”. You’ll need to count the number of calls into OnEndElement()
when string name
is equal to dict, and then look for the second call to OnEndElement()
when string name is equal to string. If you know that your xml is clean, and the string you need is always the 4th tag, then just count 4 tags.
I am certain that you can achieve the same with TinyXML. I have never used that.