【发布时间】:2020-06-13 11:21:59
【问题描述】:
我在我的 c# WindowsForm 天气 api 中使用它返回我想要从中获取节点的 xml 文件。
<current>
<city id="2988507" name="Paris">
<coord lon="2.35" lat="48.85"/>
<country>FR</country>
<timezone>7200</timezone>
<sun rise="2020-06-13T03:46:45" set="2020-06-13T19:54:52"/>
</city>
<temperature value="67.41" min="66.2" max="69.01" unit="fahrenheit"/>
<feels_like value="64.31" unit="fahrenheit"/>
<humidity value="59" unit="%"/>
<pressure value="1009" unit="hPa"/>
</current>
如果我尝试获取温度和城市的值,我没有问题,但是当我尝试获取国家/地区的值时,我得到空错误。
using (WebClient web = new WebClient())
{
string url = web.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=" + lookedCity + "&mode=xml&units="+tempType+"&appid=70e1d7c5");
XmlDocument doc = new XmlDocument();
doc.LoadXml(url);
temp = doc.DocumentElement.SelectSingleNode("temperature").Attributes["value"].Value;
country = doc.DocumentElement.SelectSingleNode("country").Value;
city = doc.DocumentElement.SelectSingleNode("city").Attributes["name"].Value;
}
【问题讨论】:
-
您试图从根元素中获取
country- 但它不是,它在city中。 (如果您格式化了 XML,这将更容易判断。)因此切换顺序以首先获取city,然后使用city.SelectSingleNode("country")。虽然我个人会使用 LINQ to XML,这会使 IMO 更简洁。