- Home /
C# XML Question
Currently I am trying to read this XML file
<?xml version=”1.0" encoding=”utf-8" ?>
<KenoNumbers>
<numbers num="1" />
<numbers num="4" />
<numbers num="32" />
<numbers num="54" />
</KenoNumbers>
Now I am fairly new to C# and using it to parse and read an XML file. Currently I am not to sure on if what I have so far actually is parsing the data and grabbing the numbers, because I am running into an issue of SerializerObj does not exist in the current state and this is also making the error of Deserialize, that error is just a ?. Below is where and I'm trying to read and store the data, but currently I'm not getting the code to run nor am I really sure if I'm actually parsing and grabbing the numbers from the XML.
public class GameManager : MonoBehaviour
{
[XmlRoot("kenoInfo")]
public class kenoInfo{
[XmlElementAttribute("num")]
public string nums;
}
void getXml () {
// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(@"C:\Users\Kyle\Downloads\yj\Assets\Script\keno.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
// Load the object saved above by using the Deserialize function
kenoInfo LoadedObj = (kenoInfo)/*issue*/SerializerObj.Deserialize(ReadFileStream);
// Cleanup
ReadFileStream.Close();
// Test the new loaded object:
Debug.Log(LoadedObj.nums);
}
Answer by WillNode · May 20, 2015 at 02:45 PM
you can do all XML Related files better with XMLDocument class.
using System.Xml // Always import this reference
public class SomeClass : MonoBehavior {
void Start(){
XmlDocument x = new XmlDocument ();
x.Load("somePath"); // Load by Path
x.LoadXml ("someXMLString"); // Load by XML String data
XmlNodeList nodeList;
XmlNode root = x.DocumentElement;
nodeList = root.SelectNodes("/Node/ChildNode"); // Find Child by XPath Expression
foreach (XmlNode node in nodeList){
Debug.Log(node);
}
}
}
see XPath examples here
newXml.Load (@"C:\Users\$$anonymous$$yle\Downloads\yj\Assets\Script\keno.xml"); // Load by Path
seems to be giving me the error XmlException: invalid encoding specification. System.Xml.XmlInputStream.Initialize (System.IO.Stream stream)
any idea why?
You have the wrong kind of quotation marks in the top of your xml file.
Also, try using relative file paths like so:
x.Load(Application.dataPath + "/Script/keno.xml");