简体   繁体   中英

How to retrieve data from Forecast API with type xml in C#?

I have to get the temperature data from an XML API store it in a variable and output it to my form. The problem is that I am getting this error and I don't know why.

Object reference not set to an instance of an object.

Is it because I am not getting the data correctly? This is my code:

string url = string.Format("http://api.openweathermap.org/data/2.5/forecast?weather?&units=metric&APPID=afa249f4910321115afd8ab0b29c3f8d&mode=xml&q=" + city);

XDocument Document = XDocument.Load(url);

WebClient webClient = new WebClient();

Temperature = (string)Document.Root.Element("forecast").Element("temperature").Attribute("value").Value;

I am getting this error in the variable Temperature. And this is from where I want to retrieve the data.

<forecast>
  <time from="2020-06-14T09:00:00" to="2020-06-14T12:00:00">
    <symbol number="500" name="light rain" var="10d"/>
    <precipitation unit="3h" value="1.21" type="rain"/>
    <windDirection deg="81" code="E" name="East"/>
    <windSpeed mps="2.48" unit="m/s" name="Light breeze"/>
    <temperature unit="celsius" value="21.73" min="20.77" max="21.73"/>
    <feels_like value="23.53" unit="celsius"/>
    <pressure unit="hPa" value="1013"/>
    <humidity value="88" unit="%"/>
    <clouds value="overcast clouds" all="99" unit="%"/>
  </time>

I got the temp using the code below:

 public string Get(string city="London")
    {
        IList<XElement> tempList;
        string temp;

        string url = string.Format("http://api.openweathermap.org/data/2.5/forecast?weather?&units=metric&APPID=afa249f4910321115afd8ab0b29c3f8d&mode=xml&q=" + city);

        XDocument Document = XDocument.Load(url);

       // WebClient webClient = new WebClient();

        var rootElement = XElement.Parse(Document.Root.ToString());
        tempList = rootElement.Element("forecast").Descendants("temperature").ToList();
        temp = tempList[0].Attribute("value").ToString();

        return temp; 

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM