从 Xml 文件加载

Loading from an Xml file

好吧,这是非常基础的,但我今天确实开始学习如何阅读 XML 文档,而且我通常会在这里找到比在线指南更全面的答案。本质上,我正在编写一个 Pokemon 游戏,它使用 XML 文件来加载所有统计数据(这是我从别人那里刷来的)。用户将输入一个 Pokemon,然后我想阅读 Pokemon 的基本统计数据来自 XML 文件,给出一个模板,这将是口袋妖怪之一:

<Pokemon>
   <Name>Bulbasaur</Name>

   <BaseStats>
     <Health>5</Health>
     <Attack>5</Attack>
     <Defense>5</Defense>
     <SpecialAttack>7</SpecialAttack>
     <SpecialDefense>7</SpecialDefense>
     <Speed>5</Speed>
   </BaseStats>
</Pokemon>

我尝试使用的代码是:

XDocument pokemonDoc = XDocument.Load(@"File Path Here");
        while(pokemonDoc.Descendants("Pokemon").Elements("Name").ToString() == cbSpecies.SelectedText)
        {
            var Stats = pokemonDoc.Descendants("Pokemon").Elements("BaseStats");
        }

但这只是 returns pokemonDoc 为 null,知道我哪里出错了吗?

注意:

cbSpeciesSelect 是用户选择他们想要的神奇宝贝种类的地方。

文件路径绝对有效,因为我已经在我的程序中使用过它

while 循环从未真正开始

你能试试下面的代码吗:

foreach(var e in pokemonDoc.Descendants("Pokemon").Elements("Name"))
{
    if(e.Value==cbSpecies.SelectedText)
    {
        var Stats = pokemonDoc.Descendants("Pokemon").Elements("BaseStats");
    }
}

尝试 xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var pokemon = doc.Descendants("Pokemon").Select(x => new {
                name = (string)x.Element("Name"),
                health = (int)x.Element("BaseStats").Element("Health"),
                attack = (int)x.Element("BaseStats").Element("Attack"),
                defense = (int)x.Element("BaseStats").Element("Defense"),
                specialAttack = (int)x.Element("BaseStats").Element("SpecialAttack"),
                specialDefense = (int)x.Element("BaseStats").Element("SpecialDefense"),
                speed = (int)x.Element("BaseStats").Element("Speed"),
            }).FirstOrDefault();
        }
    }
}