简体   繁体   English

将XML文件保存在C#中

[英]Save xml file in c#

I have a program that will take in a name and a score, it will compare the score to a scoreboard located in a xml file, and then sort it fro highest to the lowest score. 我有一个程序,它将输入名称和分数,它将分数与位于xml文件中的记分板进行比较,然后将其从最高到最低排序。 it works until i shutdown the program and restarts it, then it looks like it has not saved the changes to the xml file. 它可以正常工作,直到我关闭程序并重新启动它,然后好像它还没有将更改保存到xml文件。

this is the xml file: 这是xml文件:

<?xml version="1.0" encoding="utf-8" ?>
<Highscore>
  <Data>
    <score number="1" value="250" name="per"/>
    <score number="2" value="200" name="ole"/>
    <score number="3" value="100" name="gunnar"/>
    <score number="4" value="50" name="lars"/>
    <score number="5" value="25" name="bob"/>
  </Data>
</Highscore>

and this is the code in the program: 这是程序中的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Xml.Linq;


namespace XML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            write();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            SaveHighscore(ChechForBetterScore(LoadHighscore()));

            write();
        }

        private List<highscore> LoadHighscore()
        {
            List<highscore> temp = new List<highscore>();

            var xmlDocument = XDocument.Load("Highscore.xml");

            for(int i = 1; i <= 5; i++)
            {
                var element = xmlDocument.Root
                                .Element("Data")
                                .Elements("score")
                                .FirstOrDefault(x => (string)x.Attribute("number") == (i.ToString()));

                highscore _temp = new highscore();

                _temp.name = element.Attribute("name").Value;
                _temp.score = Convert.ToInt32(element.Attribute("value").Value);

                temp.Add(_temp);
            }

            return temp;
        }

        private List<highscore> ChechForBetterScore(List<highscore> scoreBoard)
        {
            List<highscore> temp = new List<highscore>();

            try
            {
                int userScore = Convert.ToInt32(txtScore.Text);
                string userName = txtName.Text;

                int tempScoreA = userScore;
                int tempScoreB;

                string tempNameA = userName;
                string tempNameB;

                for(int i = 0; i < scoreBoard.Count; i++)
                {
                    highscore _temp = new highscore();

                    if(scoreBoard[i].score < userScore)
                    {
                        tempScoreB = scoreBoard[i].score;
                        tempNameB = scoreBoard[i].name;

                        _temp.score = tempScoreA;
                        _temp.name = tempNameA;

                        tempScoreA = tempScoreB;
                        tempNameA = tempNameB;

                        temp.Add(_temp);
                    }

                    else
                    {
                        _temp.name = scoreBoard[i].name;
                        _temp.score = scoreBoard[i].score;

                        temp.Add(_temp);
                    }
                }

            }
            catch(Exception trown)
            {
                MessageBox.Show(trown.Message, "Error");
            }

            return temp;
        }

        private void SaveHighscore(List<highscore> scoreboard)
        {
            var xmlDocument = XDocument.Load("Highscore.xml");

            for(int i = 1; i <= 5; i++)
            {
                var element = xmlDocument.Root
                                .Element("Data")
                                .Elements("score")
                                .FirstOrDefault(x => (string)x.Attribute("number") == (i.ToString()));

                element.Attribute("name").Value = scoreboard[i - 1].name;
                element.Attribute("value").Value = (scoreboard[i - 1].score).ToString();
            }

            xmlDocument.Save("Highscore.xml");
        }

        private void write()
        {
            labOutput.Text = "";

            List<highscore> temp = LoadHighscore();

            for(int i = 0; i < temp.Count; i++)
            {
                labOutput.Text += (i + 1).ToString() + ". " + temp[i].name + ": " + (temp[i].score).ToString() + "\n";
            }
        }

        struct highscore
        {
            public int score;
            public string name;
        }
    }
}

i can't find how you get it to save it after you shut down the program, just comment if there is something that you need more information on 关闭程序后,我找不到保存它的方式,只是注释一下是否有您需要更多信息的信息

I assume that Form1 will work as main window of your application. 我假设Form1将充当您的应用程序的主窗口。 In such case you should bind callback method to application Exit event in App.xaml. 在这种情况下,您应该将回调方法绑定到App.xaml中的应用程序Exit事件。 From body of that callback method you may refer to your main window by using MainWindow property. 从该回调方法的正文中,您可以使用MainWindow属性引用主窗口。 You may cast it to Form1 type and invoke method that will save the results (make it public). 您可以将其转换为Form1类型并调用将保存结果的方法(将其公开)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM