繁体   English   中英

如何从 C# 中类型为 xml 的预测 API 中检索数据?

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

我必须从 XML API 将温度数据存储在变量中,然后将 output 存储到我的表单中。 问题是我收到了这个错误,我不知道为什么。

Object 引用未设置为 object 的实例。

是因为我没有正确获取数据吗? 这是我的代码:

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;

我在变量温度中收到此错误。 这是我要检索数据的地方。

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

我使用下面的代码得到了温度:

 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; 

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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