Weather

public class WeatherModel
    {
        #region 定义成员变量
        private string _temperature = "";
        private string _weather = "";
        private string _wind = "";
        private string _city = "";
        private DateTime _dateStart = DateTime.Now;
        private string _coldPoint = "";
        private string _weatherImagePath = "";
        private string _weatherUrl = "http://www.soso.com/tb.q?cid=tb.tq";   //远程的天气url页面地址
        #endregion

        #region 定义类属性
        /// <summary>
        /// 温度
        /// </summary>
        public string Temperature
        {
            get { return _temperature; }
            set { _temperature = value; }
        }

        /// <summary>
        /// 天气说明
        /// </summary>
        public string Weather
        {
            get { return _weather; }
            set { _weather = value; }
        }

        /// <summary>
        /// 风力
        /// </summary>
        public string Wind
        {
            get { return _wind; }
            set { _wind = value; }
        }

        /// <summary>
        /// 城市
        /// </summary>
        public string City
        {
            get { return _city; }
            set { _city = value; }
        }

        /// <summary>
        /// 起始日期
        /// </summary>
        public DateTime DateStart
        {
            get { return _dateStart; }
            set { _dateStart = value; }
        }

        /// <summary>
        /// 感冒指数
        /// </summary>
        public string ColdPoint
        {
            get { return _coldPoint; }
            set { _coldPoint = value; }
        }

        /// <summary>
        /// 天气的图片路径
        /// </summary>
        public string WeatherImagePath
        {
            get { return _weatherImagePath; }
            set { _weatherImagePath = value; }
        }

        /// <summary>
        /// 读取天气的url地址
        /// </summary>
        public string WeatherUrl
        {
            get { return _weatherUrl; }
            set { _weatherUrl = value; }
        }
        #endregion

        public WeatherModel() { }

        /// <summary>
        /// 要获得天气的城市
        /// </summary>
        /// <param name="city">城市</param>
        public WeatherModel(string city)
        {
            City = city;
        }
    }


    public class WeatherReadData
    {
        #region 定义成员变量
        private string _weatherUrl = "http://www.soso.com/tb.q?cid=tb.tq&cin=";   //远程的天气url页面地址
        #endregion

        #region 定义类属性
        /// <summary>
        /// 读取天气的url地址
        /// </summary>
        public string WeatherUrl
        {
            get { return _weatherUrl; }
            set { _weatherUrl = value; }
        }
        #endregion

        /// <summary>
        /// 获得从当天开始到后2天,共3天的天气情况
        /// </summary>
        /// <param name="city">城市</param>
        public WeatherModel[] ReadThreeDayWeather(string city)
        {
            //url的编码方式:
            //string tmp1 = System.Web.HttpUtility.UrlEncode(city, System.Text.Encoding.GetEncoding("GB2312"));
            //string tmp2 = System.Web.HttpUtility.UrlEncode(city, System.Text.Encoding.UTF8);

            WeatherUrl += "&city=" + HttpUtility.UrlEncode(city, System.Text.Encoding.GetEncoding("GB2312"));
           
            System.Net.WebClient client = new System.Net.WebClient();
            //-------------读取远程网页,将其转换为流
            Stream resStream = null;
            try
            {
                resStream = client.OpenRead(WeatherUrl);
            }
            catch { return null; }
            StreamReader streamReader = new StreamReader(resStream, System.Text.Encoding.Default);
            //---------------------

            StringBuilder strXml = new StringBuilder();
            StringBuilder strBody = new StringBuilder();
            bool isSaveXml = false;
            //读取流数据
            while (!streamReader.EndOfStream)
            {
                string tmp = streamReader.ReadLine();

                #region 读取xml
                if (tmp.Contains("<description>"))
                {
                    isSaveXml = true;
                    strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                }
                else if (tmp.Contains("</description>"))
                {
                    isSaveXml = false;
                    strXml.Append(tmp);
                }

                if (isSaveXml)
                    strXml.Append(tmp);
                #endregion

                #region 读取body中第1天的天气的数据
                if (tmp.Contains("<body>"))
                {
                    strBody.Append(tmp);
                }
                #endregion
            }

            #region 读取body中的第一个<ul>
            int ulStart = strBody.ToString().IndexOf("<ul>");
            int ulEnd = strBody.ToString().IndexOf("</ul>") + "</ul>".Length;
            string tmpStr = "";

            try
            {
                tmpStr = strBody.ToString().Substring(ulStart, ulEnd - ulStart);
            }
            catch{}

            //在第一个</li>之前加个</img>
            int liStart = tmpStr.IndexOf("</li>");
            tmpStr = tmpStr.Insert(liStart, "</img>");

            //在最前面加上xml说明
            tmpStr = tmpStr.Insert(0, "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            #endregion

            XmlDocument xmldocFirstDay = new XmlDocument();
            xmldocFirstDay.LoadXml(tmpStr);

            //将字符串转换为xml格式
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(strXml.ToString());

            WeatherModel[] modelArr = new WeatherModel[3];
            modelArr[0] = new WeatherModel();
            modelArr[1] = new WeatherModel();
            modelArr[2] = new WeatherModel();

            #region 获得第1天的天气图片以及第1天的感冒指数
            XmlNodeList nodeListFirst = xmldocFirstDay.SelectNodes("/ul/li");
            //获得图片
            XmlNodeList imgNode = nodeListFirst.Item(0).ChildNodes;
            modelArr[0].WeatherImagePath = imgNode.Item(0).Attributes["src"].InnerText;

            //获得感冒指数
            modelArr[0].ColdPoint = nodeListFirst.Item(1).InnerText.Split(":".ToCharArray())[1];
            #endregion

            #region 获得第2天,第3天的天气图片
            string tmpWeather = strBody.ToString();
            int start = tmpWeather.IndexOf("<div class=\"weather\">") + "<div class=\"weather\">".Length;
            int end = 0;
            tmpWeather = tmpWeather.Substring(start);
            //获得第2天的数据
            start = tmpWeather.IndexOf("<div class=\"weather\">") + "<div class=\"weather\">".Length;
            tmpWeather = tmpWeather.Substring(start);
            //获得第2天的图片
            start = tmpWeather.IndexOf("<img src=\"") + "<img src=\"".Length;
            end = tmpWeather.IndexOf(".png") - 6;
            modelArr[1].WeatherImagePath = tmpWeather.Substring(start, end);

            //获得第3天的数据
            start = tmpWeather.IndexOf("<div class=\"weather\">") + "<div class=\"weather\">".Length;
            tmpWeather = tmpWeather.Substring(start);
            //获得第3天的图片
            start = tmpWeather.IndexOf("<img src=\"") + "<img src=\"".Length;
            end = tmpWeather.IndexOf(".png") - 6;
            modelArr[2].WeatherImagePath = tmpWeather.Substring(start, end);
            #endregion

            #region 获得城市
            XmlNodeList nodeCity = xmldoc.SelectNodes("/description/city");
            modelArr[0].City = nodeCity.Item(0).InnerText;
            modelArr[1].City = nodeCity.Item(0).InnerText;
            modelArr[2].City = nodeCity.Item(0).InnerText;
            #endregion

            #region 日期
            //获得日期
            XmlNodeList nodeDate = xmldoc.SelectNodes("/description/date");
            modelArr[0].DateStart = Convert.ToDateTime(nodeDate.Item(0).InnerText);
            modelArr[1].DateStart = modelArr[0].DateStart.AddDays(1);
            modelArr[2].DateStart = modelArr[0].DateStart.AddDays(2);
            #endregion

            #region 获得天气
            //获得天气
            XmlNodeList nodeData = xmldoc.SelectNodes("/description/data");

            if (nodeData != null && nodeData.Count > 0)
            {
                XmlNodeList weathNodeList = nodeData.Item(0).ChildNodes;   //获得data下的所有子节点
                if (weathNodeList != null && weathNodeList.Count > 0)
                {
                    for (int i = 0; i < weathNodeList.Count; i++)
                    {
                        XmlNodeList dayNodeList = weathNodeList.Item(i).ChildNodes;  //获得today下的所有子节点

                        if (dayNodeList != null && dayNodeList.Count > 0)
                        {
                            modelArr[i].Temperature = dayNodeList.Item(0).InnerText;
                            modelArr[i].Weather = dayNodeList.Item(1).InnerText;
                            modelArr[i].Wind = dayNodeList.Item(2).InnerText;
                        }
                    }
                }
            }
            #endregion

            #region 资源释放
            xmldocFirstDay = null;
            xmldoc = null;
            resStream.Flush();
            resStream.Close();
            resStream.Dispose();
            resStream = null;
            streamReader.Close();
            streamReader.Dispose();
            streamReader = null;
            #endregion

            return modelArr;
        }
    }

调用

public partial class WeatherPage : System.Web.UI.Page
    {
        private string CityName;
        private int TimeType;
        protected void Page_Load(object sender, EventArgs e)
        {
            //城市名称
            if (!String.IsNullOrEmpty(Request.QueryString["CityName"]))
            {
                CityName = Request.QueryString["CityName"];
            }
            //时间
            TimeType = WEB.ProceFlow.ValidatorValueManage.GetIntValue(Request.QueryString["TimeType"]);

            if (!IsPostBack)
            {
                Response.Write(GetWeatherInfo(CityName, TimeType));
                Response.End();
            }
        }

        /// <summary>
        /// 获得天气信息
        /// </summary>
        /// <param name="CityName">城市名称</param>
        /// <param name="TimeType">返回的天气日期,0.今天;1,明天;2,后天</param>
        /// <returns></returns>
        /// Enow.Share.WeatherManage.WeatherModel[] modelArr = read.ReadThreeDayWeather(this.TextBox1.Text);
        /// 返回今天,明天,后天的天气 和TimeType匹配
        private string GetWeatherInfo(string CityName, int TimeType)
        {
            //Server.UrlEncode("杭州")
            string strTemp = "";
            Enow.Share.WeatherManage.WeatherReadData read = new Enow.Share.WeatherManage.WeatherReadData();
            Enow.Share.WeatherManage.WeatherModel[] modelArr = read.ReadThreeDayWeather(CityName);
            if (modelArr == null)
                return "";
            Enow.Share.WeatherManage.WeatherModel model = modelArr[TimeType];

            strTemp += string.Format("<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='30%' align='center'><img src='{0}' width='40' height='40' /></td><td width='70%' align='left'><strong  class='blue'>{1}:{2}</strong><br />感冒指数:{3}</td></tr></table>",model.WeatherImagePath,model.Weather,model.Temperature,model.ColdPoint);

            return strTemp;
        }
    }

转载于:https://www.cnblogs.com/lonelyofsoul/archive/2013/01/09/weather.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/274391.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

线框模型_进行计划之前:线框和模型

线框模型Before we start developing something, we need a plan about what we’re doing and what is the expected result from the project. Same as developing a website, we need to create a mockup before we start developing (coding) because it will cost so much…

撰写论文时word使用技巧(转)

------------------------------------- 1. Word2007 的表格自定义格式额度功能是很实用的&#xff0c;比如论文中需要经常插入表格的话&#xff0c; 可以在“表格设计”那里“修改表格样式”一次性把默认的表格样式设置为三线表&#xff0c;这样&#xff0c; 你以后每次插入的…

工作经验教训_在设计工作五年后获得的经验教训

工作经验教训This June it has been five years since I graduated from college. Since then I’ve been working as a UX designer for a lot of different companies, including a start-up, an application developer, and two consultancy firms.我从大学毕业已经五年了&a…

Wayland 源码解析之代码结构

来源&#xff1a;http://blog.csdn.net/basilc/article/details/8074895 获取、编译 Wayland 及其依赖库可参考 Wayland 官方网站的 Build 指南&#xff1a;http://wayland.freedesktop.org/building.html。 Wayland 实现的代码组成可以分成以下四部分&#xff1a; 1. Wayland…

中文排版规则_非设计师的5条排版规则

中文排版规则01仅以一种字体开始 (01 Start with only one font) The first tip for non-designers dealing with typography is simple and will make your life much easier: Stop combining different fonts you like individually and try using only one font in your fut…

基本响应性的Web设计测试工具

在重新设计页面的过程中。要使页面完全响应的设计&#xff08;这意味着它会重新调整大小根据浏览器的尺寸和方向&#xff09;。如iPhone和iPad的移动电话和平板电脑我碰到了一些非常方便的响应设计工具&#xff0c;帮我测试网站在不同的屏幕响应。下面的这些响应的网页设计工具…

ux设计_声音建议:设计UX声音的快速指南

ux设计Mating calls, warning grunts, and supportive coos are some of the sounds heard throughout the animal kingdom. All species use finely-tuned noises to communicate to one another and inform others of an action or behavior. We humans aren’t all that dif…

css3高级和低级样式属性先后顺序

写css hack 时&#xff0c;由于hack主要针对的是个别浏览器&#xff0c;hack的书写顺序应当是从一般到特殊的写法。 如&#xff1a; .box { width:200px; height:200px; position:fixed; left:0; top:0; _position:absolute; } 如果颠倒顺序&#xff0c;从特殊到一般&#xff0…

sans serif_Sans和Serif相遇可爱

sans serifI first noticed it in this tweet. Exciting upcoming product and snazzy motion work aside, “What a fascinating logotype!”, I exclaimed!我在此推文中首先注意到了它。 我惊呼即将推出的激动人心的产品和令人眼花&#xff0c;乱的动作&#xff0c;“多么迷人…

[ckeditor系列]ckeditor 自己写的一个简单的image上传js 运用iframe的ajax上传

ckeditor最近修改一个上传的&#xff0c;原来的Image的上传插件功能很多&#xff0c;但是自己用&#xff0c;没有必要&#xff0c;就进行了修改&#xff0c;后来就改成了目前的样子&#xff0c;根据_samples/api_dialog.html 进行了修改&#xff0c;把页面里面的调用都进行了修…

sql 避免除0错误_设计简历时避免这3个常见的UX错误

sql 避免除0错误重点 (Top highlight)Having a great looking resume on hand is very important when you’re looking for a job. It is your ticket to land the interview that will get you one step closer to that one job you’ve been dreaming of.在找工作时&#xf…

一个网站自动化测试程序的设计与实现

CSDN博客不再经常更新&#xff0c;更多优质文章请来 粉丝联盟网 FansUnion.cn! (FansUnion) 代码 下载地址&#xff1a;http://download.csdn.net/detail/fansunion/5018357(免积分) 代码亮点&#xff1a;可读性很好&#xff0c;注释详尽 背景 工作中&#xff0c;在维护一…

如何编写数据库可视化界面_编写用于数据可视化的替代文本

如何编写数据库可视化界面什么是替代文字 (What is Alt Text) Alt text (sometimes called Alt tags or alternative text) are written descriptions added to images that convey the meaning of the visual. Good alt text helps more people understand the content. Assis…

(转)swc与swf的区别

在Flash Builder中用Actionscript写的类可以打包成swc或swf&#xff0c; 在Flash CS中制作的元件也可以打包成swc或swf文件&#xff0c; 一个swc或swf文件中可以包含多个类或元件&#xff0c; 每个元件会映射成一个类&#xff0c; 因此&#xff0c;在Flash Builder中的类和在Fl…

js 验证各种格式类型的正则表达式

<script src"scripts/jquery-1.4.1.js" type"text/javascript"></script> <script language"javascript" type"text/javascript"> /** * 定义验证各种格式类型的正则表达式对象 */ var Regexs { email: …

reloaddata 跳动_纸跳动像素

reloaddata 跳动I would like to open with a problem.我想开一个问题。 Why are so many designer going straight to pixels?为什么这么多设计师直接使用像素&#xff1f; Over the past few years i’ve witnessed this in my team, my clients and others throughout th…

使用自定义RadioButton和ViewPager实现TabHost效果和带滑动的页卡效果。

参考自http://www.apkbus.com/android-86125-1-1.html 这篇文章技术含量一般&#xff0c;大家别见笑。源码我以测试&#xff0c;在底部可下载。 好了先上效果图&#xff1a; 以下是实现步骤&#xff1a; 1、准备自定义RadioButton控件的样式图片等&#xff0c;就是准…

利益相关者软件工程_改善开发人员团队与非技术利益相关者之间交流的方法

利益相关者软件工程Whether you’re working on a startup or a big company, keeping your stakeholders and non-technical partners engaged and up to date on what the tech team has been building can be hard.无论您是在初创公司还是大公司中工作&#xff0c;都要让您的…

Hibernate的检索策略

Hibernate的Session在加载一个Java对象时&#xff0c;可以将与这个对象相关联的其他Java对象都加载到缓存中&#xff0c;以便程序及时调用。但有些情况下&#xff0c;我们不需要加载太多无用的对象到缓存中&#xff0c;一来这样会撑爆内存&#xff0c;二来增加了访问数据库的次…

响应式网格项目动画布局_响应式网格及其实际使用方式:常见的UI布局

响应式网格项目动画布局重点 (Top highlight)第二部分 (Part II) Now that you have a basic understanding of how to use grids, you might be wondering how to apply them to layouts you see on the web. Responsive grids are a method to systematically align your des…