Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read xml from URL

Tags:

c#

xml

This is what I have so far. I am trying to just read the XML from the URL and just get for example temperature, humidity....etc.... But every time I try something else it gives me an error. I want to retrieve the information and put it in a label.

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"));
        }
    }
}
like image 756
locoss Avatar asked Feb 15 '13 22:02

locoss


1 Answers

It took me a bit of trial and error but I've got it. In C# make sure you are using - using System.Xml;

Here is the code using wunderground API. In order for this to work make sure you sign up for a key other wise it will not work. Where is say this your_key that is where you put in your key. It should look like something like this. I used a button and three labels to display the information.

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;
            }



        }
    }
}

When you press the button you will get the information displayed in the labels assign. I am still experimenting and you are able to have some sort of refresh every so often instead of pressing the button every time to get an update.

like image 106
locoss Avatar answered Nov 15 '22 04:11

locoss