从google's天气API中提取XML数据
本文关键字:API 提取 XML 数据 天气 google | 更新日期: 2023-09-27 18:10:59
我一直在使用这个代码来尝试从谷歌天气API获取数据,但我从来没有得到甚至接近拔出我想要的。
我的目标是看:
<forecast_information>
**<city data="london uk"/>**
<postal_code data="london uk"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2011-10-09"/>
<current_date_time data="2011-10-09 12:50:00 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Partly Cloudy"/>
<temp_f data="68"/>
**<temp_c data="20"/>**
**<humidity data="Humidity: 68%"/>**
<icon data="/ig/images/weather/partly_cloudy.gif"/>
**<wind_condition data="Wind: W at 22 mph"/>**
</current_conditions>
并且只返回子节点的文本。
所以结果是:
城市:英国伦敦温度:20 c湿度:68%风:22英里
目前我正在尝试使用这个,但是无处可去…
XmlDocument doc = new XmlDocument();
XmlNodeList _list = null;
doc.Load("http://www.google.com/ig/api?weather=london+uk");
_list = doc.GetElementsByTagName("forecast_information/");
foreach (XmlNode node in _list)
{
history.AppendText(Environment.NewLine + "City : " + node.InnerText);
}
//注意,当前代码设置为显示所有子节点
也许有人能解释一下这件事?也许你应该用node.SelectSingleNode("city").Attributes["data"].Value
而不是node.InnerText
——编辑
XmlDocument doc = new XmlDocument();
doc.Load("http://www.google.com/ig/api?weather=london+uk");
var list = doc.GetElementsByTagName("forecast_information");
foreach (XmlNode node in list)
{
Console.WriteLine("City : " + node.SelectSingleNode("city").Attributes["data"].Value);
}
list = doc.GetElementsByTagName("current_conditions");
foreach (XmlNode node in list)
{
foreach (XmlNode childnode in node.ChildNodes)
{
Console.Write(childnode.Attributes["data"].Value + " ");
}
}
更改为
history.AppendText(Environment.NewLine + "City : " + node.GetAttribute("data"));
using System.Xml.Linq;
using System.Xml.XPath;
XElement doc = XElement.Load("http://www.google.com/ig/api?weather=london+uk");
string theCity = doc.XPathSelectElement(@"weather/forecast_information/city").Attribute("data").Value;
string theTemp = doc.XPathSelectElement(@"weather/current_conditions/temp_c").Attribute("data").Value;
string theHumid = doc.XPathSelectElement(@"weather/current_conditions/humidity").Attribute("data").Value;
string theWind = doc.XPathSelectElement(@"weather/current_conditions/wind_condition").Attribute("data").Value;
string resultString = String.Format("City : {0} Temp : {1}c {2} {3}", theCity, theTemp, theHumid, theWind);