1

我一直在使用这段代码尝试从谷歌天气 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>

并且只返回子节点的文本。

所以结果是:

城市:英国伦敦 温度:20c 湿度:68% 风速:22mph

目前我正在尝试使用它,但无处可去......

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

//注意,当前代码设置为显示所有子节点

也许有人可以对此事有所了解?

4

3 回答 3

2

也许你应该使用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 + " ");
    }
}
于 2011-10-09T15:31:42.603 回答
0

将其更改为

history.AppendText(Environment.NewLine + "City : " + node.GetAttribute("data"));
于 2011-10-09T15:35:01.743 回答
0
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);
于 2011-10-09T16:00:05.773 回答