views:

300

answers:

1

I am making a small card game which required a high score list that is saved to an external file, and loaded from it at the begining of each each game.

I wrote an xml file in this format

bob 10 3:42 21-09-09

I have figured out how to create a dataset, use dataset.readxml, to load the xml into it, create a row and then write each row into an array of HighScore's

class HighScore { string nameString, timeString, dateString; int scoreInt; }

i have also figured out how to check if the games highscore is higher than the lowest in the array,

im working on the sort, but want i would like to know is how to get the HighScore[] array back into a dataset then into the xml, or even from the array straight to the dataset any help is much appreciated, i have tried to google it, but i havent found what i want

+1  A: 

Do you really need to use a DataSet just to serialize your array? If you only need to serialize an array you can use simple Xml Serialization. Here's an example:

    [XmlRoot("highScore")]
    public class HighScore
    {
        [XmlElement("name")]
        public string Name { get; set; }
        [XmlElement("dateTime")]
        public DateTime Date { get; set; }
        [XmlElement("score")]
        public int Score { get; set; }
    }

    static void Main(string[] args)
    {

        IList<HighScore> highScores = new[] { 
            new HighScore {Name = "bob", Date = DateTime.Now, Score = 10 },
            new HighScore {Name = "john", Date = DateTime.Now, Score = 9 },
            new HighScore {Name = "maria", Date = DateTime.Now, Score = 28 }
        };


        // serializing Array
        XmlSerializer s = new XmlSerializer(typeof(HighScore[]));
        using (Stream st = new FileStream(@"c:\test.xml", FileMode.Create))
        {
            s.Serialize(st, highScores.ToArray());
        }

        // deserializing Array
        HighScore[] highScoresArray;
        using (Stream st = new FileStream(@"c:\test.xml", FileMode.Open))
        {
            highScoresArray = (HighScore[])s.Deserialize(st);
        }

        foreach (var highScore in highScoresArray)
        {
            Console.WriteLine("{0}, {1}, {2} ", highScore.Name, highScore.Date, highScore.Score);
        }
    }
bruno conde