2016-12-15 4 views
0

私はhttp://api.met.no/weatherapi/locationforecast/1.9/?lat=49.8197202;lon=18.1673554 XMLを処理しようとしています。 各温度要素のすべての値属性を選択したいとします。C#XmlDocument選択ノードが空に戻ります

私はこれを試しました。

 const string url = "http://api.met.no/weatherapi/locationforecast/1.9/?lat=49.8197202;lon=18.1673554"; 
     WebClient client = new WebClient(); 
     string x = client.DownloadString(url); 
     XmlDocument xml = new XmlDocument(); 
     xml.LoadXml(x); 

     XmlNodeList nodes = xml.SelectNodes("/weatherdata/product/time/location/temperature"); 
     //XmlNodeList nodes = xml.SelectNodes("temperature"); 

     foreach (XmlNode node in nodes) 
     {     
      Console.WriteLine(node.Attributes[0].Value); 
     } 

しかし、私はいつも何も得られません。何が間違っているのですか?

+0

あなたの文書にこのメモが存在しない可能性があります。 XDocument – mybirthname

+0

も使用してください。私はXmlDocumentクラスを使用する必要があります。私は学校のプロジェクトとその必要な指定のためにそれを行う必要があります。 – gygabyte

答えて

0

現行の単一スラッシュは、ルートの下のweatherdataをターゲットにしていますが、ルートはweatherdataです。

はダブルスラッシュ作るためにあなたのXPathクエリに前のスラッシュを追加します。

XmlNodeList nodes = xml.SelectNodes("//weatherdata/product/time/location/temperature"); 

ダブルスラッシュを関係なく、彼らがどこにあるかの選択と一致していない現在のノードからドキュメント内のノードを選択するために、XPathを伝えます。

又は先行スラッシュ削除:

XmlNodeList nodes = xml.SelectNodes("weatherdata/product/time/location/temperature"); 

根を含む全経路を探します。また

、あなたは明らかと呼ばれる値が値にこれを追加したいので、:

Console.WriteLine(node.Attributes["value"].Value); 

node.Attributesので値導入[0] .Valueのは、あなたが期待するためにではないかもしれません。

0

各属性をループしていますか?

foreach (XmlNode node in nodes) 
     { 
      //You could grab just the value like below 
      Console.WriteLine(node.Attributes["value"].Value); 

      //or loop through each attribute 
      foreach (XmlAttribute f in node.Attributes) 
      { 
       Console.WriteLine(f.Value); 
      } 
     } 
+0

私は推測しています。しなければならない? – gygabyte

+0

が編集されました。あなたの質問を編集した –

関連する問題