2016-12-11 16 views
-1

これは基本的なものですが、今日はXML文書を読む方法を文字通り学習し始めました。通常、オンラインガイドよりもここではより包括的な答えが見つかります。基本的には、XMLファイルを使用してすべての統計情報を読み込むポケモンゲームをコーディングしています。ユーザーはポケモンを入力してから、ポケモンの基本統計をXMLファイルから読み込みます、テンプレートを与えるために、これはポケモンの1のようになります。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> 

コードIVEが使用しようとした次のとおりです。

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

が、これはちょうど、NULLとしてイムが間違って任意のアイデアをpokemonDocを返します。 ?

注:

cbSpeciesSelectユーザーは自分の欲しいポケモンのどの種の選択場所です。私は私のプログラムですでにそれを使用していたとして

ファイルパスは間違いなく、whileループが実際に

+0

xmlファイルに 'xml declaration'がありますか? –

+0

xmlファイルの先頭には次のような内容があります。 '<?xml version =" 1.0 "encoding =" utf-8 "?>

+1

最初の手順としてオブジェクトに直接シリアル化/逆シリアル化する方がクリーンかもしれません。 (https://msdn.microsoft.com/en-us/library/182eeyhh(v=vs.110).aspx) – stead

答えて

1

の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(); 
     } 
    } 
} 
1

を開始したことがない

に動作しますが、コードの下に試すことができます:

foreach(var e in pokemonDoc.Descendants("Pokemon").Elements("Name")) 
{ 
    if(e.Value==cbSpecies.SelectedText) 
    { 
     var Stats = pokemonDoc.Descendants("Pokemon").Elements("BaseStats"); 
    } 
} 
関連する問題