C# Pull XML data from google's weather API

冷暖自知 提交于 2020-01-11 12:28:45

问题


I've been using this code to try and get data from the google weather API, but I never get even close to pulling out what i want.

My goal is to look at:

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

And only return the text of the child nodes.

So the result would be:

City: London UK Temp: 20c Humidity: 68% Wind: 22mph

Currently I am trying to use this, but got nowhere...

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

//NOTE, currently code is set to display ALL child nodes

Perhaps someone can shed some light on the matter?


回答1:


Maybe you should use node.SelectSingleNode("city").Attributes["data"].Value instead of node.InnerText

--EDIT-- This works for me

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



回答2:


Change that to

history.AppendText(Environment.NewLine + "City : " + node.GetAttribute("data"));



回答3:


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


来源:https://stackoverflow.com/questions/7704437/c-sharp-pull-xml-data-from-googles-weather-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!