How do I save and read XML data?

How do I save and read XML data?

Postby Leeizazombie » 13 Apr 2014, 19:38

I've been looking trough Google but I don't understand it, I want to for example save a players title under his name in the XML file then read it by making a command read the title by his name... or is there better ways to save data like that?
Owner of:
LeeIzaZombie Freebuild and Lava Survival V2 (Shut Down and updated)
LeeIzaZombie Survival (Comming back soon)

Contact:
Skype: leeizazombie
IRC: irc.geekshed.net, #leeizazombie, #mcclassichosting
User avatar
Leeizazombie
 
Posts: 536
Joined: 10 Jun 2013, 17:45
Location: Ireland.

Re: How do I save and read XML data?

Postby dzienny » 14 Apr 2014, 14:01

It depends on what you want to achieve. If you want to store data for all the players, then the best solution would be to create a new table in the database and store data there. You would have to learn SQL.

If you want to just serialize some limited in size data, then you can use XmlSerializer. Example:
Code: Select all
public class PlayerInfo
{
    public string Name { get; set; }
    public string Title { get; set; }
}

static readonly string TitlePath = "title.xml";

...

// Create a PlayerInfo instance.
var pi = new PlayerInfo { Name = "LeeIzaZombie", Title = "Zombie" };

// Initialize XmlSerializer.
var s = new XmlSerializer(pi.GetType());

// Create a TitlePath file to store the serialized data.
using (var xw = XmlWriter.Create(TitlePath, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = true }))
{
    // Serialize to a TitlePath file.
    s.Serialize(xw, pi);
}

// Create a variable to store retrieved data.
PlayeInfo retrieved = null;

// Open a TitlePath file.
using (var xr = XmlReader.Create(TitlePath))
{
    // Deserialize a TitlePath file.
    retrieved = (PlayerInfo)s.Deserialize(xr);
}
User avatar
dzienny
Administrator
 
Posts: 1181
Joined: 23 Jan 2011, 14:27

Re: How do I save and read XML data?

Postby joppiesaus » 14 Apr 2014, 14:06

I had the same problem. I believe Dzienny had made XML examples in this forum... But I'm not sure.
Anyways I don't like XML, even thought I should learn it. ;)

I have made my own config(I actually made 4 of sorts of configs, all of them are different, but I picked this one):
Don't expect much from it(read the first comment ;) ). Feel free to edit it.
There are multiple types of get():
Code: Select all
object get(string key) // Will check if it exists, returns it as a bool/string/object/float/int
void get(string key, int/string/float/bool defaultValue, ref thing) // checks it and will always return: if it doesn't exist, the default value will get set to the key and the default value will be passed to ref thing.


Code: Select all
using System;
using System.IO;

namespace Config
{
    // This is just awefull. Written in one night. But it works well!
    class JConfig
    {
        public string path;
        public string[] lines;
        public string[] newFileLines;

        public JConfig(string config, string[] startingLines)
        {
            this.path = Directory.GetCurrentDirectory() + "\\" + config;
            this.newFileLines = startingLines;
            checkFile();
            initLines();
        }

        private void initLines()
        {
            using (StreamReader read = new StreamReader(path))
            {
                this.lines = read.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            }
        }

        // get("player", "player1", ref player);
        #region get
        public object get(string key)
        {
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].StartsWith("//")) continue; // Not really needed, but...

                string[] split = lines[i].Split('=');
               
                if (split[0] == key && split.Length > 1)
                {
                    if (split[1] == "true") return true;
                    else if (split[1] == "false") return false;

                    int num;
                    bool isNum = int.TryParse(split[1], out num);

                    if (isNum) return num;

                    float f;
                    bool isFloat = float.TryParse(split[1], out f);

                    if (isFloat) return f;

                    return split[1];
                }
            }

            return null; // NULL NULL NULL NULL
        }

        public void get(string key, object defaultValue, ref object obj)
        {
            var thing = get(key);
            if (thing == null)
            {
                set(key, defaultValue);
                obj = defaultValue;
            }
            else if (thing.GetType() == defaultValue.GetType()) obj = thing;
            else obj = defaultValue; // Computer will never come here
        }

        public void get(string key, int defaultValue, ref int obj)
        {
            object b = (object)obj;
            get(key, defaultValue, ref b);
            obj = (int)b;
        }

        public void get(string key, string defaultValue, ref string obj)
        {
            object b = (object)obj;
            get(key, defaultValue, ref b);
            obj = (string)b;
        }

        public void get(string key, bool defaultValue, ref bool obj)
        {
            object b = (object)obj;
            get(key, defaultValue, ref b);
            obj = (bool)b;
        }

        public void get(string key, float defaultValue, ref float obj)
        {
            object b = (object)obj;
            get(key, defaultValue, ref b);
            obj = (float)b;
        }
        #endregion

        public void set(string key, object value)
        {
            checkFile();

            byte minus = 1;
            if (lines.Length == 1)
            {
                lines = newFileLines;
                minus = 0;
            }

            using (StreamWriter write = new StreamWriter(path))
            {
                for (int i = 0; i < lines.Length - minus; i++) write.WriteLine(lines[i]);
                write.WriteLine(key.ToString() + "=" + value.ToString());
            }

            initLines();
        }

        public void checkFile()
        {
            if (!File.Exists(path)) using (File.Create(path)) { }
        }
    }
}
joppiesaus
 
Posts: 379
Joined: 20 Aug 2012, 07:28
Location: in a obsedian house, with glass in it so i can see the lava!

Re: How do I save and read XML data?

Postby dzienny » 15 Apr 2014, 12:45

It's a nice config saver. Well, it could strongly benefit from some refactoring. But it's still useful <ok>
User avatar
dzienny
Administrator
 
Posts: 1181
Joined: 23 Jan 2011, 14:27


Return to Help in Coding

Who is online

Users browsing this forum: No registered users and 1 guest

cron