Google API 天气数据缓存到一个XML中

//通过Google API 获取天气数据 并读取存入 XML中 

private void CreateXML()
{
XmlNodeList weekList = GetWeatherXML();
string strXml = "<weather></weather>";
doc.LoadXml(strXml);

foreach (var obj in weekList)
{
XmlNode xmlNode = obj as XmlNode;
XmlElement newElem = doc.CreateElement("forecast_conditions");
doc.DocumentElement.AppendChild(newElem);
XmlElement weekElem = doc.CreateElement("day_of_week");
weekElem.InnerText = xmlNode.SelectSingleNode("day_of_week").Attributes["data"].InnerText;
doc.LastChild.LastChild.AppendChild(weekElem);
XmlElement lowElem = doc.CreateElement("low");
lowElem.InnerText = xmlNode.SelectSingleNode("low").Attributes["data"].InnerText;
doc.LastChild.LastChild.AppendChild(lowElem);
XmlElement highElem = doc.CreateElement("high");
highElem.InnerText = xmlNode.SelectSingleNode("high").Attributes["data"].InnerText;
doc.LastChild.LastChild.AppendChild(highElem);
XmlElement iconElem = doc.CreateElement("icon");
iconElem.InnerText = xmlNode.SelectSingleNode("icon").Attributes["data"].InnerText;
doc.LastChild.LastChild.AppendChild(iconElem);
XmlElement conditionElem = doc.CreateElement("condition");
conditionElem.InnerText = xmlNode.SelectSingleNode("condition").Attributes["data"].InnerText;
doc.LastChild.LastChild.AppendChild(conditionElem);
}

doc.PreserveWhitespace = true;
doc.Save("data.xml");
}

//在APP.Config中添加AppSetting key 方便替换Google API的访问地址的修改

<configuration>
<appSettings>
<add key="googleAPI" value="http://www.google.com.hk/ig/api?hl=zh-cn#weather="/>
</appSettings>
</configuration>

//通过API 获取谷歌的天气数据信息 

public XmlNodeList GetWeatherXML()
{
string con = ConfigurationManager.AppSettings["googleAPI"].ToString();
string googleAPI = con.Replace("#", "&").ToString();
XmlNodeList weekList = null;
try
{
XmlDocument xmlDocument = GoogleWeatherAPI_ParserXML(@googleAPI);
weekList = xmlDocument.SelectNodes("xml_api_reply/weather/forecast_conditions");


}
catch
{
} return weekList;
}

//解析XML 通过Google API 获取天气数据

private XmlDocument GoogleWeatherAPI_ParserXML(string baseUrl)
{
HttpWebRequest GWP_Request;
HttpWebResponse GWP_Response = null;
XmlDocument GWP_XMLdoc = null;
try
{
GWP_Request = (HttpWebRequest)WebRequest.Create(string.Format(baseUrl));
GWP_Request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
GWP_Response = (HttpWebResponse)GWP_Request.GetResponse();
GWP_XMLdoc = new XmlDocument();
GWP_XMLdoc.Load(GWP_Response.GetResponseStream());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
GWP_Response.Close();
return GWP_XMLdoc;
}

//更新XML中的数据信息

private void UpdateXML()
{
string strXmlPath = Application.StartupPath + "\\data.xml";
doc.Load(strXmlPath);
xe = doc.FirstChild as XmlElement;
XmlNode xnRC = xe.LastChild.LastChild.SelectSingleNode("day_of_week");
if (xnRC != null)
{
xnRC.InnerText = "星期八";
doc.Save(strXmlPath);
}
}

原文地址:https://www.cnblogs.com/chaoa/p/2382303.html