2013-02-15 80 views
3

這就是我目前爲止的內容。我試圖從URL中讀取XML,例如溫度,溼度等....但是每次我嘗試別的時候都會給我一個錯誤。我想檢索信息並將其放入標籤中。從URL中讀取xml

namespace WindowsFormsApplication1 { 
    public partial class Form1: Form { 
     public Form1() { 
      InitializeComponent(); 
     } 
     private void btnSubmit_Click(object sender, EventArgs e) { 
      String zip = txtZip.Text; 
      XmlDocument weatherURL = new XmlDocument(); 
      weatherURL.Load("http://api.wunderground.com/api/" 
      your_key "/conditions/q/" + zip + ".xml"); 
      foreach(XmlNode nodeselect in weatherURL.SelectNodes("response/current_observation")); 
     } 
    } 
} 
+0

顯示XML的樣子以及您試圖從中解析出哪些準確的信息。 – 2013-02-15 22:09:27

+2

「它給我一個錯誤」是永遠不夠的信息 - 請參閱http://tinyurl.com/so-list – 2013-02-15 22:14:19

+0

0.1 http://www.wunderground.com/weather/api/d/terms .html PST America/Los_Angeles -0800多雲 72 F(22.2 C) locoss 2013-02-16 00:28:21

回答

12

這花了我一些嘗試和錯誤,但我知道了。在C#中,確保使用System.Xml使用 - ;

這裏是使用wunderground API的代碼。爲了這個工作,確保你註冊一個關鍵其他明智的,它不會工作。在哪裏說這是你的鑰匙,這是你放入鑰匙的地方。它應該看起來像這樣。我用一個按鈕和三個標籤來顯示信息。

namespace wfats2 

{ 

    public partial class Form1 : Form 

{ 

public Form1() 

     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 

      XmlDocument doc1 = new XmlDocument(); 
      doc1.Load("http://api.wunderground.com/api/your_key/conditions/q/92135.xml"); 
      XmlElement root = doc1.DocumentElement; 
      XmlNodeList nodes = root.SelectNodes("/response/current_observation"); 

      foreach (XmlNode node in nodes) 
      { 
       string tempf = node["temp_f"].InnerText; 
       string tempc = node["temp_c"].InnerText; 
       string feels = node["feelslike_f"].InnerText; 

       label2.Text = tempf; 
       label4.Text = tempc; 
       label6.Text = feels; 
      } 



     } 
    } 
} 

當您按下按鈕時,您將獲得顯示在標籤分配中的信息。我仍在試驗,你可以每隔一段時間進行一次刷新,而不是每次按下按鈕以獲得更新。

0

首先是的,你需要提供更多的信息在你的問題,但我可以看到,你的URL中有「your_key」。您可能需要使用您的API密鑰替換它才能使用。

+1

我有一個鍵,但不知道使用哪個參數來獲取某些元素。 (不想把我的鑰匙給大家使用) – locoss 2013-02-15 23:39:29

+0

foreach(weatherURL.SelectNodes中的XmlNode nodeselect(「response/current_observation」));沒有做別的。你有什麼錯誤,你想做什麼?提供您正在獲取的xml示例以及您想要的字段。 – 2013-02-15 23:44:15