- Home /
C# Deserializing XML and Assigning Values
Hi everyone, I have been working on a modified version of the Save and Load from XML U3 Collections. I made it so it saved values and load values. I managed to get the save part done but the load part I'm not sure how to setup. I want to make it so when I click on the load button that it loads the XML file and the values from the XML file are assigned to the values within the script.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;
public class _GameSaveLoad1: MonoBehaviour {
// An example where the encoding can be found is at
// http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
// We will just use the KISS method and cheat a little and use
// the examples from the web page since they are fully described
// This is our local private members
bool _ShouldSave, _ShouldLoad,_SwitchSave,_SwitchLoad;
string _FileLocation,_FileName;
UserData1 myData;
string _data;
public float exampleFloat = 1.25f;
public string exampleString ="Giraffe";
public int exampleInt = 5;
public bool exampleBool = false;
public string[] exampleArray = new string[]{"A","B","C","D"};
public List <int> exampleList = new List<int>();
// When the EGO is instansiated the Start will trigger
// so we setup our initial values for our local members
void Start () {
exampleList.Add(1);
exampleList.Add(2);
exampleList.Add(3);
exampleList.Add(4);
// We setup our rectangles for our messages
// Where we want to save and load to and from
_FileLocation=Application.dataPath;
_FileName="SaveData.xml";
// we need soemthing to store the information into
myData=new UserData1();
}
void Update () {}
void OnGUI()
{
//***************************************************
// Loading The Player...
// **************************************************
if (GUILayout.Button("Load")) {
// Load our UserData into myData
LoadXML();
if(_data.ToString() != "")
{
// notice how I use a reference to type (UserData) here, you need this
// so that the returned object is converted into the correct type
myData = (UserData1)DeserializeObject(_data);
// set the players position to the data we loaded
// just a way to show that we loaded in ok
}
}
//***************************************************
// Saving The Player...
// **************************************************
if (GUILayout.Button("Save")) {
myData._iUser.ExampleFloat = exampleFloat;
myData._iUser.ExampleString = exampleString;
myData._iUser.ExampleInt = exampleInt;
myData._iUser.ExampleBool = exampleBool;
myData._iUser.ExampleArray = exampleArray;
myData._iUser.ExampleList = exampleList;
// Time to creat our XML!
_data = SerializeObject(myData);
// This is the final resulting XML from the serialization process
CreateXML();
Debug.Log(_data);
}
}
/* The following metods came from the referenced URL */
string UTF8ByteArrayToString(byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
string constructedString = encoding.GetString(characters);
return (constructedString);
}
byte[] StringToUTF8ByteArray(string pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
// Here we serialize our UserData object of myData
string SerializeObject(object pObject)
{
string XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(UserData1));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
// Here we deserialize it back into its original form
object DeserializeObject(string pXmlizedString)
{
XmlSerializer xs = new XmlSerializer(typeof(UserData1));
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);
}
// Finally our save and load methods for the file itself
void CreateXML()
{
StreamWriter writer;
FileInfo t = new FileInfo(_FileLocation+"\\"+ _FileName);
if(!t.Exists)
{
writer = t.CreateText();
}
else
{
t.Delete();
writer = t.CreateText();
}
writer.Write(_data);
writer.Close();
Debug.Log("File written.");
}
void LoadXML()
{
StreamReader r = File.OpenText(_FileLocation+"\\"+ _FileName);
string _info = r.ReadToEnd();
r.Close();
_data=_info;
Debug.Log("File Read");
}
}
// UserData is our custom class that holds our defined objects we want to store in XML format
public class UserData1
{
// We have to define a default instance of the structure
public DemoData _iUser;
// Default constructor doesn't really do anything at the moment
public UserData1() { }
// Anything we want to store in the XML file, we define it here
public struct DemoData
{
public float ExampleFloat;
public string ExampleString;
public int ExampleInt;
public bool ExampleBool;
public string[] ExampleArray;
public List <int> ExampleList;
}
}
Here is what the XML file Looks like.
<?xml version="1.0" encoding="utf-8"?>
<UserData1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<_iUser>
<ExampleFloat>1.25</ExampleFloat>
<ExampleString>Giraffe</ExampleString>
<ExampleInt>5</ExampleInt>
<ExampleBool>false</ExampleBool>
<ExampleArray>
<string>A</string>
<string>B</string>
<string>C</string>
<string>D</string>
</ExampleArray>
<ExampleList>
<int>1</int>
<int>2</int>
<int>3</int>
<int>4</int>
</ExampleList>
</_iUser>
</UserData1>
Now that the data is saved how would I access the values and assign them?
Answer by JerryCCAD · May 26, 2016 at 07:52 PM
Use a deserialization method to extract your data from an xml file. Maybe this example will help
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Learning how to deserialize xml file 1 Answer
C# Saving Values to XML 1 Answer
Movement Script Help 1 Answer