Help Load & RW Xml

hi guys thanks for your reply :slight_smile:

I speak French

sorry
I send you the code:

Game1:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Android.Content.Res;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace processXml
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;

    private SpriteFont _font;

    //gestion scores

    private long _score=0;
    private long score2=0;
    private long score3=0;

    // private ScoreManager _scoreManager;

    private float _timer;

    private Random random;

    public string recup;

    public static string _fileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);


    private List<Score> HighScores { get; set; }

    private List<Score> CurrentScore { get; set; }
    private List<Score> Scores { get; set; }


   
    public Game1()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;

        random = new Random();

        Scores = new List<Score>();



        //load scores
        /* highScores = new List<Score>
         {
             new Score("Dave:", _score),

         };*/

        //classer ordre decroissant

        // HighScores = HighScores.OrderByDescending(c => c.Value).ToList();

        //créer dossier si il n'est pas existant
        /*  if (!Directory.Exists(_fileName))
               Directory.CreateDirectory(_fileName);*/

        //use serializer XML

        /* XmlSerializer xs = new XmlSerializer(typeof(List<Score>));

          //Write in XML File

          using(StreamWriter sw = new StreamWriter($"{_fileName}/test.xml"))
          {

              xs.Serialize(sw, HighScores);
          }

          //init highScores
         // HighScores = null;

          //Read file XML

          using (StreamReader sr = new StreamReader($"{_fileName}/test.xml"))
          {
              HighScores = (List<Score>)xs.Deserialize(sr);

          }*/

        //takes the first 5elements

        // HighScores = Scores.Take(5).ToList();
        // HighScores = null;

        //call read write xml
       // WriteXml();
        HighScores = null;
       // ReadXml();


    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
        _font = Content.Load<SpriteFont>("Font");
        _timer = 5;
        /* HighScores = new List<Score>

             {
             new Score("player1:",_score),
             new Score("player2",score2),
             new Score("player3",score3),

             };*/
         ReadXml();

       

    }


    //read xml

    public void ReadXml()
    {

        //use serializer XML

        XmlSerializer xs = new XmlSerializer(typeof(List<Score>));
       
        //Read file XML

        using (StreamReader sr = new StreamReader($"{_fileName}/test.xml"))
        {
            HighScores = (List<Score>)xs.Deserialize(sr);

        }
        

    }

    //write xml

    public void WriteXml()
    {
        //use serializer XML

        XmlSerializer xs = new XmlSerializer(typeof(List<Score>));
        using (StreamWriter sw = new StreamWriter($"{_fileName}/test.xml"))
        {

            xs.Serialize(sw, HighScores);
        }

    }
    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        _score = random.Next(0, 100); // Returns a random number from 0-99
        score2 = random.Next(0, 100);
        score3 = random.Next(0, 100);

        _timer -= (float)gameTime.ElapsedGameTime.TotalSeconds;

        // If the round is over
        if (_timer <= 0)
        {
            HighScores = new List<Score>

            {
            new Score("Player:",_score),
            new Score("Player2:",score2),
           
            new Score("player3",score3),

            };

       HighScores = HighScores.OrderByDescending(c => c.Value).ToList();
            _timer = 5;
            // _score = 0;

          WriteXml();
        }
        

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here

        _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied);

        _spriteBatch.DrawString(_font, "Score: " + _score, new Vector2(10, 10), Color.Red);
        _spriteBatch.DrawString(_font, "Time: " + _timer.ToString("N2"), new Vector2(10, 30), Color.Red);

      _spriteBatch.DrawString(_font, "Highscores:\n" + string.Join("\n", HighScores.Select(c => c.PlayerName + ": " + c.Value).ToArray()), new Vector2(50, 50), Color.Red);

        
       // _spriteBatch.DrawString(_font, "coucou" + recup, new Vector2(50, 50), Color.White);
        _spriteBatch.End();

        base.Draw(gameTime);
    }
}

}

TestClass: for save score xml

using System;
namespace processXml
{
[Serializable]
public class TestClass
{

    public string Name { get; set; }
    public long Score { get; set; }
    
    //constructor
    public TestClass()
    {
    }
    public TestClass(string name, long score)
    {
        Name = name;
        Score = score;
    }
}

}

thanks in advance :slight_smile:

1 Like

Hello, I hope you are well ? i wanted to know if there is something wrong with the code? am i allowed to call these redxml () and writexml functios this way? when I call my functions in the main program what I put in comments it works I manage to install the app but as soon as I try to read the xml file in LoadContent () it crashes :frowning: Thanks for your help

Are you matching your saving and loading data?
Faites-vous correspondre à vos données d’enregistrement et de chargement ?

Hello
thanks for the reply and the translation :slight_smile:

I put the scores in the list

maybe but I don’t know how to fix it I think that could be the problem
HighScores = new List

        {
        new Score ("Player:", _ score),
        new Score ("Player2:", score2),
       
        new Score ("player3", score3),

        };

You keep changing this and it does not match up with the other two… seems suspect.
Vous continuez à changer cela et il ne correspond pas avec les deux autres … semble suspect.

Also…
Également…

I understand

tell you about the testClass funcion
while I call Score?

From what I have seen, your code is not very consistent.
D’après ce que j’ai vu, votre code n’est pas très cohérent.

the idea is to add the score to the xml file then I display the best score when starting the app

I tested the read and write functions separately
it works

you are right there is one it is not consistent

I have to take over the algo
already serialization and deseialization work
the class testClass seems to react well

afterwards it’s less clear to me.

this code works to load and save xml file in android memory location

I thank Charles for his help :slight_smile:
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
IsMouseVisible = true;

random = new Random();

public static string _fileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

//créer dossier si il n’est pas existant
if (!Directory.Exists(_fileName))
Directory.CreateDirectory(_fileName);
//load scores
highScores = new List
{
new Score(“Dave:”, _score),

 };

//classer ordre decroissant

HighScores = HighScores.OrderByDescending(c => c.Value).ToList();



//use serializer XML

 XmlSerializer xs = new XmlSerializer(typeof(List<Score>));

  //Write in XML File

  using(StreamWriter sw = new StreamWriter($"{_fileName}/test.xml"))
  {

      xs.Serialize(sw, HighScores);
  }

  //init highScores
  HighScores = null;

  //Read file XML

  using (StreamReader sr = new StreamReader($"{_fileName}/test.xml"))
  {
      HighScores = (List<Score>)xs.Deserialize(sr);

  }

}

now I don’t know how to load at startup and be consistent with the algorithm so that I can install the app in real life without any problem

Hopefully, someone else can assist further now…

I need to revisit XML handling soon, but now with Core… I am screwed lol

lol good luck
thank you for giving me your time
have a good day, see you soon

i hope i will be able to fix this one day lol

1 Like

That code looks like you are overwriting the text.xml file every time the game runs, so saved scores will be lost…

1 Like

Hello for the first or second code? how to remedy this? and when I put the logic of serialization deserialization save and load in the readXml () and writeXml () functions to facilitate the program is it good or it can create the problem because as soon as I call reading and writing outside of game1 the app does not install so there are two problems the first my code logic and the second installation problem I imagine which also relates to the code thanks a lot for your help :slight_smile:

Your Gam1 class runs, and the first thing you do is replace the contents of the xml file with the hard coded score list… Just don’t do that…

1 Like

It was a test In the first code with the test class I initialize like this public Game1 () { _graphics = new GraphicsDeviceManager (this); Content.RootDirectory = “Content”; IsMouseVisible = true; random = new Random (); Scores = new list (); …} Is that better or shouldn’t the score list be declared here at all? This is what you say

tell you about highscore hard initialize in Game1? highScores = new List { new Score (“Dave:”, _score), };

Start

Check if file exists
If file does not exist => create file
If file exists => load data

Do other stuff
Game loop start

Hi
I do it in Game1

if (!Directory.Exists(_fileName))
Directory.CreateDirectory(_fileName);

do I have to call it somewhere else? thank you :slight_smile:

Where are you placing it…

EDIT

Is that just checking for the directory or the file as well?