C#实现简单的天气预报示例代码

这篇文章主要介绍了C#实现简单的天气预报示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

本来是打算用C#爬取天气网站上的信息,然后用正则表达过滤有用信息的,但是很淦,正则表达式太难了。无意间找到添加web引用的方式来获取天气信息,亲自测试后发现效果尚可,就记录一下。

引用部分

由于本次是控制台应用,就没有页面设计了。在VS中新建控制台程序后,右击“引用”――“添加服务引用”。

在“添加服务引用”左下角选择“高级”。

在“服务引用设置中”选择左下角的“添加web引用”。

在其中输入天气预报提取网址的url:

http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

至此,引用功能就已完成。该网站提供了很多查询方法,此处我们使用的是getWeatherCityName(),方法详细内容如下:

当然,你也可以转到该url查看更多定义,选择适合你的方法。

代码实现部分

Main方法里直接引用:

 WeatherWebService myweather = new WeatherWebService(); string[] myweathers = myweather.getWeatherbyCityName("郑州"); for (int i = 0; i 

传入的值尽量不要带“市”,返回的数组循环输出后结果如下:

其中各项所代表的含义可以查看上方官网的说明,这里为了让布局好看一点,让重点突出一点,可以使用到控制台的字体颜色转换语句:

 Console.ForegroundColor = ConsoleColor.颜色;

完善后的代码如下:

 WeatherWebService myweather = new WeatherWebService(); string[] myweathers = myweather.getWeatherbyCityName("郑州"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("今日天气:\n更新时间:" + myweathers[4]); Console.WriteLine("当前选择地区:" + myweathers[0] + "_" + myweathers[1] + "\n"); Console.ForegroundColor = ConsoleColor.White; Console.Write(myweathers[6] + "(今日) 风向&风力:" + myweathers[7]); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" 气温:" + myweathers[5] + "\n"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("当前实况(数据每2.5小时左右自动更新一次):\n" + myweathers[10] + myweathers[11]); Console.Write(myweathers[13] + "(明天) 风向&风力:" + myweathers[14]); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" 气温:" + myweathers[12] + "\n"); Console.ForegroundColor = ConsoleColor.White; Console.Write(myweathers[18] + "(后天) 风向&风力:" + myweathers[19]); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" 气温:" + myweathers[17] + "\n"); Console.ForegroundColor = ConsoleColor.White;

当然,你也可以在后面加一个判断,输入1的话可以查询其他城市,然后获取输入的值,传入方法中。如果感兴趣的话可以看一下源码,这里就不再过多展示。

运行效果

结语

程序很小,仅作分享。不足之处,望见谅。

项目源码:请别抢我闪刀姬/天气预报

以上就是C#实现简单的天气预报示例代码的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程