Search code examples
c#asp.netxmlweather-api

How to display XML values in list box or how to display on label.?


The given below is my code to get weather details from world weather online. The code is working fine and I get the weather details to the variable "WP_XMLdoc". But the problem is the variable contains the values are in xml format.So how can I get each value seperatly and how to display those values on label or textbox.

public static XmlDocument WeatherAPI(string sLocation)
{
    HttpWebRequest WP_Request;
    HttpWebResponse WP_Response = null;
    XmlDocument WP_XMLdoc = null;
    string sKey = "********************"; //The API key generated by World Weather Online
    string sRequestUrl = "http://api.worldweatheronline.com/free/v1/weather.ashx?format=xml&"; //The request URL for XML format

    try
    {
        //Here we are concatenating the parameters
        WP_Request = (HttpWebRequest)WebRequest.Create(string.Format(sRequestUrl + "q=" + sLocation + "&key=" + sKey));
        WP_Request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
        //Making the request
        WP_Response = (HttpWebResponse)WP_Request.GetResponse();
        WP_XMLdoc = new XmlDocument();
        //Assigning the response to our XML object
        WP_XMLdoc.Load(WP_Response.GetResponseStream());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    WP_Response.Close();

    return WP_XMLdoc; // Here we get the five values from the website in xml format. Now I want   those xml values from this "WP_XMLdoc" variable to diplay on textbox or labels.

Solution

  • The best you can use is XDocument object that gives you better control over XmlDocument.

    Here is the console application that I wrote through.

    The main method you will be using is Element(...) and Descendents(...);

    using System;
    using System.Linq;
    using System.Net;
    using System.Xml;
    using System.Xml.Linq;
    
    public class Program
    {
        public static void Main()
        {
           var result =  WeatherAPI("London");
    
            // loop throw all weather instances... 
            foreach (var w in result.Descendants("weather"))
            {
                Console.WriteLine("Weather");
                Console.WriteLine("=================");
                foreach (var e in w.Elements())
                {
                    Console.WriteLine(string.Format("Key {0} - Value {1}", e.Name, e.Value));
                }
            }
    
            // if you want to select specific element then use this.
            var currentCondition = result.Descendants("current_condition").FirstOrDefault();
            if (currentCondition != null)
            {
                Console.WriteLine("Current Condition");
                Console.WriteLine("=================");
                foreach (var e in currentCondition.Elements())
                {
                    Console.WriteLine(string.Format("Key {0} - Value {1}", e.Name, e.Value));
                }
            }
    
            Console.ReadLine();
        }
    
        public static XDocument WeatherAPI(string sLocation)
        {
            HttpWebRequest webRequest;
            HttpWebResponse webResponse = null;
            XDocument xmlResult = null;
            var apiKey = "Your key"; //The API key generated by World Weather Online
            var apiEndpoint = "http://api.worldweatheronline.com/free/v1/weather.ashx?format=xml&";
    
            try
            {
                //Here we are concatenating the parameters
                webRequest =
                    (HttpWebRequest) WebRequest.Create(string.Format(apiEndpoint + "q=" + sLocation + "&key=" + apiKey));
                webRequest.UserAgent =
                    @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
                //Making the request
                webResponse = (HttpWebResponse) webRequest.GetResponse();
                xmlResult = XDocument.Load(webResponse.GetResponseStream());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
    
    
            return xmlResult;
                // Here we get the five values from the website in xml format. Now I want   those xml values from this "WP_XMLdoc" variable to diplay on textbox or labels.
        }
    }
    

    XML output

    <data>
      <request>
        <type>City</type>
        <query>London, United Kingdom</query>
      </request>
      <current_condition>
        <observation_time>04:53 AM</observation_time>
        <temp_C>17</temp_C>
        <temp_F>63</temp_F>
        <weatherCode>143</weatherCode>
        <weatherIconUrl><![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0006_mist.png]]></weatherIconUrl>
        <weatherDesc><![CDATA[Mist]]></weatherDesc>
        <windspeedMiles>6</windspeedMiles>
        <windspeedKmph>9</windspeedKmph>
        <winddirDegree>20</winddirDegree>
        <winddir16Point>NNE</winddir16Point>
        <precipMM>0.0</precipMM>
        <humidity>94</humidity>
        <visibility>1</visibility>
        <pressure>1014</pressure>
        <cloudcover>75</cloudcover>
      </current_condition>
      <weather>
        <date>2014-09-20</date>
        <tempMaxC>22</tempMaxC>
        <tempMaxF>71</tempMaxF>
        <tempMinC>10</tempMinC>
        <tempMinF>50</tempMinF>
        <windspeedMiles>8</windspeedMiles>
        <windspeedKmph>13</windspeedKmph>
        <winddirection>N</winddirection>
        <winddir16Point>N</winddir16Point>
        <winddirDegree>350</winddirDegree>
        <weatherCode>119</weatherCode>
        <weatherIconUrl><![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png]]></weatherIconUrl>
        <weatherDesc><![CDATA[Cloudy ]]></weatherDesc>
        <precipMM>0.6</precipMM>
      </weather>
    </data>
    

    Output:

    enter image description here

    What is the Difference between Element and Descendent.

    Elements finds only those elements that are direct descendents, i.e. immediate children.

    Descendants finds children at any level, i.e. children, grand-children, etc...