Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Ochreous · Dec 22, 2012 at 01:04 AM · c#xmldeserialization

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

10 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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

C# Non-Static Member Rigidbody2D.MovePosition 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges