XML文档未从Web URL加载 - NullReferenceException

时间:2016-05-28 16:41:21

标签: c# xml

我想将openweathermap.org的API中的天气信息作为XML文档加载。

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

loadWeatherBtn_Click方法是另一个类的一部分。输出是:

> 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

输出中显示的生成的URL工作正常,为什么不加载?程序是否需要等待它首先加载(xml doc的计算时间仅为0.0085秒)?

1 个答案:

答案 0 :(得分:1)

我必须假设this.ForecastWeatherXml的类型为XmlDocument,即使您发布的代码未显示该声明。

基于此,您的主要问题是使用{em>期望XML字符串作为输入的LoadXml()方法。 MSDN

尝试使用从指定的网址加载XML文档的方法Load()

this.ForecastWeatherXml.Load(ForecastWeatherUrl);

MSDN