2016-12-15 82 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

編輯。看到你編輯你的問題 –