一个关于天气预报的VS2010C#编程,如何把天气,风向转化为代码呢?
如题 一个关于天气预报的VS2010C#编程,如何把天气,风向转化为代码呢?
比如我通过下面的代码测出是:天气:晴天;温度:026;风向:南;风速:04
我自己规定下十几种天气里,晴天是01,温度零上为0**,零下为1**,风向有8种,南为01
则输出一串代码串:01026001
这样测出的代码就可以和另外一个模块通信了。
也就是我需要把天气,温度,风向,风速编译成特殊的代码,然后编个协议就可以通信了。
如何做呢?
我编好的天气查询代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
namespace WeatherApiTest
{
class Program
{
static void Main(string[] args)
{
bool iscontinue = false; //判断是否再次查询
string cityName = "changsha";
do
{
Console.Write("天气查询软件(首次查询有联网时间,请稍后)Tea.大龙\n\r请输入要查询城市的拼音(首次默认changsha,之后为上一次输入,回车键即可)\n\r:");
iscontinue = true;
if (iscontinue)
{
string temp = Console.ReadLine().Trim();//控制台输入的城市拼音
if (!string.IsNullOrEmpty(temp))
{
cityName = temp;
}
}
Console.WriteLine();
XmlDocument xmlDocument = GoogleWeatherAPI_Parser(@"http://www.google.com/ig/api?hl=zh-cn&weather=" + cityName);
try
{
XmlNodeList dayinfo = xmlDocument.SelectNodes("xml_api_reply/weather/current_conditions");
Console.WriteLine(cityName + ": 天气:" + dayinfo[0].SelectSingleNode("condition").Attributes["data"].InnerText +
" " + dayinfo[0].SelectSingleNode("humidity").Attributes["data"].InnerText +
" " + dayinfo[0].SelectSingleNode("wind_condition ").Attributes["data"].InnerText);
XmlNodeList weekList = xmlDocument.SelectNodes("xml_api_reply/weather/forecast_conditions");//获取forecast_conditions节点的List集合
///SelectSingleNode(“”)获取节点根据节点名称
foreach (var obj in weekList)
{
XmlNode xmlNode = obj as XmlNode;
Console.WriteLine(xmlNode.SelectSingleNode("day_of_week").Attributes["data"].InnerText + " "
+ xmlNode.SelectSingleNode("condition ").Attributes["data"].InnerText + " "
+ xmlNode.SelectSingleNode("low").Attributes["data"].InnerText + "-"
+ xmlNode.SelectSingleNode("high").Attributes["data"].InnerText + " ");
}
}
catch (Exception)
{
Console.WriteLine("请检查一下城市拼音是否正确!");
}
Console.WriteLine("是否重新查询? (是Y/否N)");
string str = Console.ReadLine();
iscontinue = str.ToUpper() != "N";
} while (iscontinue);
}
/// <summary>
/// 获取城市天气的XML文东
/// </summary>
/// <param name="baseUrl">url路径</param>
/// <returns></returns>
private static XmlDocument GoogleWeatherAPI_Parser(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;
}
}
}
//谢谢各位大神了!在线等!