Having a problem reading/writing to an xml file. Error I’m getting is “Data at the root level is invalid” so assuming I’ve got something wrong with root node of XML doc? Code checks to see if a settings file exists and if not writes a copy from the default read-only version in Assets folder on creation.
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "GameSettings.xml");
if (!File.Exists(filename))
{
var xsr = new XmlSerializer(typeof(GameData));
using (StreamReader sr = new StreamReader(Android.App.Application.Context.Assets.Open("GameSettings.xml")))
{
gameData = (GameData)xsr.Deserialize(sr);
}
// Save game settings
var xsw = new XmlSerializer(typeof(GameData));
using (StreamWriter sw = new StreamWriter(filename))
{
xsw.Serialize(sw, gameData);
sw.WriteLine(xsw);
}
}
I think that much runs ok but is it making a change to the root node as it writes it?
// Load game settings
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "GameSettings.xml");
var xsr = new XmlSerializer(typeof(GameData));
using (StreamReader sr = new StreamReader(filename))
{
gameData = (GameData)xsr.Deserialize(sr);
}
// XDocument xDoc = XDocument.Load(filename);
Then when a player opens the settings screen it should read the locally generated file. If I comment out the StreamReader and use XDoc.Load() it throws the same error so I think the SteamReader code is good.
Throws the error at line:
gameData = (GameData)xsr.Deserialize(sr);
Here’s the GameSettings.xml
<?xml version="1.0" encoding="utf-8" ?>
<GameData xmlns="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<strDifficulty>Medium</strDifficulty>
<strSound>On</strSound>
</GameData>
The GameData class.
[Serializable]
public class GameData
{
public string strDifficulty { get; set; }
public string strSound { get; set; }
public GameData()
{
}
public GameData(string difficulty, string sound)
{
strDifficulty = difficulty;
strSound = sound;
}
}
Any suggestions how I’m nerfing the root node?
Thanks.