0

I want to load weather information from openweathermap.org's API as an XML document.

public Weather()
    {
        /* Generates custom weather URL */
        this.UrlStub= @"http://api.openweathermap.org/data/2.5/forecast/daily?q=";
        this.Location = "glasgow,uk";
        this.ApiKey = "&APPID=6911e84eacde075fdbdfaf05b9a2aaf5";
        this.Mode = "&mode=xml";
        this.ForecastWeatherUrl = urlStub + location + apiKey + mode;
    }
public bool loadXML()
    {
        /* Loads XML info from web */
        try
        {
            this.ForecastWeatherXml.LoadXml(ForecastWeatherUrl);
            return true;
        }
        catch (System.NullReferenceException ex)
        {
            Console.Out.WriteLine("Error loading xml Doc\n" + ex.StackTrace);
            return false;
        }
    }
private void loadWeatherBtn_Click(object sender, EventArgs e)
    {
        Weather weather = new Weather();
        Console.Out.WriteLine(weather); // prints generated xml URL
        if (weather.loadXML())
        {
            Console.Out.WriteLine("XML Loaded");
        }

The loadWeatherBtn_Click method is part of a different class. The output is:

> Weather URL: http://api.openweathermap.org/data/2.5/forecast/daily?q=glasgow,uk&APPID=6911e84eacde075fdbdfaf05b9a2aaf5&mode=xml
Error loading xml Doc
   at Al_Fresgow.Weather.loadXML() in C:\ROOTDIRECTORY\APPNAME\APPNAME\Weather.cs:line 163

The generated URL shown in the output works correctly so why isn't this loading?? Does the program need to wait for it to load first (calculation time for xml doc is only 0.0085 secs)?

Andy G
  • 18,518
  • 5
  • 42
  • 63
DMcDonald
  • 89
  • 13

1 Answers1

1

I have to assume that the type of this.ForecastWeatherXml is XmlDocument, even though your posted code does not show that declaration.

Based on that, your primary problem is the use of the LoadXml() method which expects an XML string as the input. MSDN

Try using the method Load() which loads the XML document from the specified URL:

this.ForecastWeatherXml.Load(ForecastWeatherUrl);

MSDN

David Tansey
  • 5,203
  • 4
  • 27
  • 47
  • Thanks for your help. I'd set the field 'code'(XmlDocument forecastWeatherXml;) but hadn't initialized it as 'code' (this.forecastWeatherXml = new XmlDocument();) It now works, thanks again – DMcDonald May 28 '16 at 21:28