- Home /
Load Xml on Android with XmlReader
Hello,
I'm developing an Android app at the moment and need to load unit data. I chose xml files to store this data, and it works perfectly fine on PC. On Android it doesn't work and I guess the reason for that is the way I load the xml files frm the resource folder:
XmlReader reader = XmlReader.Create(Application.dataPath + "/Resources/XML/Units/" + Dicts.UnitTypeToString(unitType) + ".xml");
xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
reader.Close();
Do you know why this doesn't work? Or should I load my Xml files differently?
Thanks for your help!
Answer by vladrybak · Sep 26, 2015 at 11:51 AM
This is how i save and load my class PluginParameters
Save File:
XmlSerializer serialWrite = new XmlSerializer( typeof(PluginParameters));
Stream stream = new FileStream(Application.dataPath + "/Resources/PluginParams/plugin_config.xml", FileMode.Create , FileAccess.Write );
serialWrite.Serialize (stream, pluginParameters);
stream.Close();
Load file:
XmlSerializer parametersSerializer = new XmlSerializer(typeof(PluginParameters));
Stream reader = new MemoryStream( (Resources.Load("PluginParams/plugin_config", typeof(TextAsset)) as TextAsset).bytes );
StreamReader textReader = new StreamReader(reader);
pluginParameters = (PluginParameters) parametersSerializer.Deserialize( textReader );
reader.Dispose();
Thank you, so I guess loading the xml as a TextAsset and converting it to an XmlDocument later might be a solution to my problem. I still wonder why my method doesn't work though.
Answer by Deranged-Mind · Dec 16, 2015 at 08:34 AM
I've just been struggling with this problem as well. It turns out that in order to read XML data on an Android device, you need to load the TextAsset from your Resources folder.
Create a folder in your Assets folder named
Resources
and place your XML file into that folder.Load the TextAsset using Resources.Load(). Use the name of the file without adding the extension (e.g., "firstlevel") and cast it as a TextAsset.
Create an XmlSerializer for your class (my class type was Map, yours will probably be different)
Then create a stream for your code to Deserialize your XML code.
TextAsset levelXML = (TextAsset)Resources.Load("FileNameWithoutExtension", typeof(TextAsset));
XmlSerializer serializer = new XmlSerializer(typeof(Map));
using (var stream = new MemoryStream(levelXML.bytes)) { map = (Map)serializer.Deserialize(stream); }
Doesn't look like my code wants to format correctly, but if you're still having problems, lemme know! :-)