- Home /
How do I make this XML file parser work in Unity
Hello, I am trying desperately to get this to output anything in Unity and it is just not working...
using System;
using System.Xml;
using UnityEngine;
using UnityEngine.UI;
namespace ParseXML
{
class PARSEMATH : MonoBehaviour
{
static void Main(string[] args)
{
Debug.Log("Hello");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("..\\..\\testing.xml");
Debug.Log("testing");
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
{
string text = node.InnerText;
Console.WriteLine(node.InnerText);
Debug.Log("testing");
Debug.Log(node.InnerText);
}
}
}
}
This is the file I am using that needs to be parsed.
<mrow>
<apply>
<eq/>
<apply>
<plus/>
<apply>
<power/>
<ci>x</ci>
<cn>2</cn>
</apply>
<apply>
<times/>
<cn>4</cn>
<ci>x</ci>
</apply>
<cn>4</cn>
</apply>
<cn>0</cn>
</apply>
</mrow>
The parser seems to work differently to how I assumed.
This should work. $$anonymous$$aybe your file isn't being loaded properly because if you just load the xml string in directly it works fine.
XmlDocument xmlDoc = new XmlDocument()
{
InnerXml = @"
<mrow>
<apply>
<eq/>
<apply>
<plus/>
<apply>
<power/>
<ci>x</ci>
<cn>2</cn>
</apply>
<apply>
<times/>
<cn>4</cn>
<ci>x</ci>
</apply>
<cn>4</cn>
</apply>
<cn>0</cn>
</apply>
</mrow>
"
};
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
{
Debug.Log(node.InnerText); // Inside Unity
Console.WriteLine(node.InnerText); // Inside normal .NET app
}
Answer by Bunny83 · Jan 26, 2020 at 01:52 PM
Because you don't write an application from scratch. There is no "Main" method in Behaviour components. If you want to execute your code when your game starts / enters play mode you should put your code inside the Awake or Start callback.
Besides the fact that your code in question wasn't be executed at all, another issue might be what you actually expect to get printed. Your root node is your "mrow" node. Its only child node is an "apply" node. You then print its "InnerText" property all you would get is the combined text of the nodes. Something like "x24x40"
. I see that this is actually the mathematical equation x² + 4x + 4 = 0
in prefix notation. What you actually want to do with this is up to you.
Your answer
Follow this Question
Related Questions
Invalid Encoding Specification Xml 1 Answer
XML parsing c# in unity 1 Answer
How to Shortly Reset a XML File and Class VariablesTo Create New Game 0 Answers
Multiple Cars not working 1 Answer
Read AND Write to XML at runtime 1 Answer