简体   繁体   English

如何加载 XML 文件的属性

[英]How to load a property of an XML-file

I want to load the highscore of an XML file and spend the first place in a label.我想加载highscore文件的高分,并在 label 中获得第一名。 How do I manage to read the first entry and spend its value?我如何设法阅读第一个条目并花费其价值?

public class Highscore_obj
{
    public string Name { get; set; }
    public int Score { get; set; }
}


class Highscore
{
    public Highscore_obj[] Score_array = new Highscore_obj[4];

    public void LoadXmL(string path)
    {
        XmlDocument XML = new XmlDocument();
        using (Stream s = File.OpenRead(path))
        {
            XML.Load(s);
        }

        Score_array[0].Name = "Alex";
        Score_array[0].Score = 1000;

        Score_array[1].Name = "Chris";
        Score_array[1].Score = 940;

        Score_array[2].Name = "Stefan";
        Score_array[2].Score = 700;

        XmlNodeList Highscores = XML.ChildNodes;

    }

When I start my game the Highscore of Alex must be visible in the label.当我开始我的游戏时,Alex 的Highscore必须在 label 中可见。

Instead of an Array I would rather suggest using a List.我宁愿建议使用列表而不是数组。 Then you can use Linq to query your list and sort by score descending.然后您可以使用 Linq 查询您的列表并按分数降序排序。 I would also rather use serialization and deserialization to load and store your List to and from XML.我也宁愿使用序列化和反序列化来加载和存储您的列表到 XML。

The code below illustrates this and should get you on the right track.下面的代码说明了这一点,应该让你走上正轨。

    internal List<Highscore> Highscores { get; set; }

    public void LoadXmL(string path)
    {
        List<Highscore> highscores = null;

        XmlSerializer ser = new XmlSerializer(typeof(List<Highscore>));

        using (XmlReader reader = XmlReader.Create(path))
        {
            highscores = (List<Highscore>)ser.Deserialize(reader);
        }

        if (highscores == null)
        {
            highscores = new List<Highscore>
            {
                new Highscore{ Name = "Alex", Score = 1000 },
                new Highscore{ Name = "Chris", Score = 940 },
                new Highscore{ Name = "Stefan", Score = 700 },
            };
        }

    }

    public class Highscore
    {
        public string Name { get; set; }
        public int Score { get; set; }
    }

    public Highscore GetHighest()
    {
        return Highscores.OrderByDescending(o => o.Score).First();
    }

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

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