且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

yahoo OPEN api测试之weather feed

更新时间:2022-09-27 09:52:44

 昨天写了个googlefeed api应用,突然对rss蛮感兴趣的,天生比较好奇,以前都是做windows程序感觉进入互联网领域,象是走进另外一扇大门,更加有趣,更加丰富多彩.先展示一下结果
yahoo OPEN api测试之weather feed
调用feed api最主要要学习的知识是RSS读取的问题.
         .NET框架提供了System.Xml.Serialization.XmlSerializer类型,为将对象序列化为XML或将XML序列化为对象提供了很大支持。
         下面我们针对yahoo weather feed api,通过实例讲解一下如何读取RSS文件。
         首先通过yahoo weather feed api
         "http://xml.weather.yahoo.com/forecastrss?p=" & p & "&u=" & U
     可以得到如下RSS文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
         <channel>
                   <title>Yahoo! Weather - Hangzhou, CH</title>
                  <link>http://us.rd.yahoo.com/dailynews/rss/weather/Hangzhou__CH/*http://weather.yahoo.com/forecast/CHXX0044_f.html</link>
                   <description>Yahoo! Weather for Hangzhou, CH</description>
                   <language>en-us</language>
                   <lastBuildDate>Fri, 27 Feb 2009 12:30 pm CST</lastBuildDate>
                   <ttl>60</ttl>
                   <yweather:location city="Hangzhou" region="" country="CH" />
                   <yweather:units temperature="F" distance="mi" pressure="in" speed="mph" />
                   <yweather:wind chill="39" direction="20" speed="7" />
                   <yweather:atmosphere humidity="81" visibility="1.86" pressure="30.27" rising="0" />
                   <yweather:astronomy sunrise="6:28 am" sunset="5:57 pm" />
                   <image>
                            <title>Yahoo! Weather</title>
                            <width>142</width>
                            <height>18</height>
                            <link>http://weather.yahoo.com</link>
                            <url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url>
                   </image>
                   <item>
                            <title>Conditions for Hangzhou, CH at 12:30 pm CST</title>
                            <geo:lat>30.23</geo:lat>
                            <geo:long>120.17</geo:long>
                            <link>http://us.rd.yahoo.com/dailynews/rss/weather/Hangzhou__CH/*http://weather.yahoo.com/forecast/CHXX0044_f.html</link>
                            <pubDate>Fri, 27 Feb 2009 12:30 pm CST</pubDate>
                            <yweather:condition text="Rain Shower" code="11" temp="43" date="Fri, 27 Feb 2009 12:30 pm CST" />
                            <description>
                                     <![CDATA[
                                     <img src="http://l.yimg.com/a/i/us/we/52/11.gif"/>
                                     <br />
                                     <b>Current Conditions:</b>
                                     <br />
                                     Rain Shower, 43 F<BR />
                                     <BR />
                                     <b>Forecast:</b>
                                     <BR />
                                     Fri - Rain. High: 42 Low: 39<br />
                                     Sat - Rain. High: 43 Low: 40<br />
                                     <br />
                                     <a href="Full'>http://us.rd.yahoo.com/dailynews/rss/weather/Hangzhou__CH/*http://weather.yahoo.com/forecast/CHXX0044_f.html">Full Forecast at Yahoo! Weather</a>
                                     <BR/>
                                     (provided by The Weather Channel)<br/>
                                     ]]>
                            </description>
                            <yweather:forecast day="Fri" date="27 Feb 2009" low="39" high="42" text="Rain" code="12" />
                            <yweather:forecast day="Sat" date="28 Feb 2009" low="40" high="43" text="Rain" code="12" />
                            <guid isPermaLink="false">CHXX0044_2009_02_27_12_30_CST</guid>
                   </item>
         </channel>
</rss>
<!-- api4.weather.sp1.yahoo.com uncompressed/chunked Thu Feb 26 21:00:04 PST 2009 -->
 
 
 
如上文所说.NET框架提供了System.Xml.Serialization.XmlSerializer类型,现在我们要做的就是如何利用xmlSerializer将XML序列化为对象。
         对于上面的XML文件为了便于对象序列化我们会做如下替换
        
    str = str.Replace("yweather:", "")
        str = str.Replace("geo:", "")
        'Dim str1 As String = """  : "
 
        Dim str1 = "isPermaLink=""false"""
        str = str.Replace(str1, "")
        str1 = " version=""2.0"" xmlns:yweather=""http://xml.weather.yahoo.com/ns/rss/1.0"" xmlns:geo=""http://www.w3.org/2003/01/geo/wgs84_pos#"""
        str = str.Replace(str1, "")
 
 
接着我们需要按照xml的格式,将所有的节点定义为对象,并将节点的属性定义为对象的属性。
         如该RSS中需要先定义rss对象
        
Imports Microsoft.VisualBasic
Imports System.Xml.Serialization
Partial Class YahooWeatherForecast
 
    <XmlRoot("rss")> _
       Public Class rssClass
        Private _channel As channelClass
 
        <XmlElement()> _
        Public Property channel() As channelClass
            Get
                Return _channel
            End Get
            Set(ByVal value As channelClass)
                _channel = value
            End Set
        End Property
    End Class
End Class
 
在该对象中包含chanelClass,保持和xml的文件相同的结构
接下来我们需要定义chanelClass,代码如下:
Imports Microsoft.VisualBasic
Imports System.Xml.Serialization
Partial Class YahooWeatherForecast
    Partial Class rssClass
        Partial Class channelClass
            Private _title As String
            ''' <summary>
            '''  The title of the feed, which includes the location city. For example "Yahoo! Weather - Sunnyvale, CA"
            ''' </summary>
            <XmlElement()> _
            Public Property title() As String
                Get
                    Return _title
                End Get
                Set(ByVal value As String)
                    _title = value
                End Set
            End Property
 
 
            Private _link As String
            ''' <summary>
            '''  The URL for the Yahoo! Weather page of the forecast for this location. For example http://us.rd.yahoo.com/dailynews/rss/weather/ Sunnyvale__CA/ *http://xml.weather.yahoo.com/ forecast/94089_f.html
            ''' </summary>
            <XmlElement()> _
            Public Property link() As String
                Get
                    Return _link
                End Get
                Set(ByVal value As String)
                    _link = value
                End Set
            End Property
 
            Private _language As String
            ''' <summary>
            '''  The language of the weather forecast, for example, en-us for US English.
            ''' </summary>
            <XmlElement()> _
            Public Property language() As String
                Get
                    Return _language
                End Get
                Set(ByVal value As String)
                    _language = value
                End Set
            End Property
 
            Private _description As String
            ''' <summary>
            '''  The overall description of the feed including the location, for example "Yahoo! Weather for Sunnyvale, CA"
            ''' </summary>
            <XmlElement()> _
            Public Property description() As String
                Get
                    Return _description
                End Get
                Set(ByVal value As String)
                    _description = value
                End Set
            End Property
 
            Private _lastBuildDate As String
            ''' <summary>
            '''  The last time the feed was updated. The format is in the date format defined by RFC822 Section 5, for example Mon, 256 Sep 17:25:18 -0700.
            ''' </summary>
            <XmlElement()> _
            Public Property lastBuildDate() As String
                Get
                    Return _lastBuildDate
                End Get
                Set(ByVal value As String)
                    _lastBuildDate = value
                End Set
            End Property
 
            Private _ttl As String
            ''' <summary>
            '''  Time to Live; how long in minutes this feed should be cached.
            ''' </summary>
            <XmlElement()> _
            Public Property ttl() As String
                Get
                    Return _ttl
                End Get
                Set(ByVal value As String)
                    _ttl = value
                End Set
            End Property
 
            Private _location As locationClass
            ''' <summary>
            '''  The location of this forecast.
            ''' </summary>
            <XmlElement()> _
            Public Property location() As locationClass
                Get
                    Return _location
                End Get
                Set(ByVal value As locationClass)
                    _location = value
                End Set
            End Property
 
            Private _units As unitsClass
            ''' <summary>
            '''  Units for various aspects of the forecast.
            ''' </summary>
            <XmlElement()> _
            Public Property units() As unitsClass
                Get
                    Return _units
                End Get
                Set(ByVal value As unitsClass)
                    _units = value
                End Set
            End Property
 
            Private _wind As windClass
            ''' <summary>
            '''  Forecast information about wind.
            ''' </summary>
            <XmlElement()> _
            Public Property wind() As windClass
                Get
                    Return _wind
                End Get
                Set(ByVal value As windClass)
                    _wind = value
                End Set
            End Property
 
            Private _atmosphere As atmosphereClass
            ''' <summary>
            '''  Forecast information about current atmospheric pressure, humidity, and visibility.
            ''' </summary>
            <XmlElement()> _
            Public Property atmosphere() As atmosphereClass
                Get
                    Return _atmosphere
                End Get
                Set(ByVal value As atmosphereClass)
                    _atmosphere = value
                End Set
            End Property
 
            Private _astronomy As astronomyClass
            ''' <summary>
            '''  Forecast information about current astronomical conditions.
            ''' </summary>
            <XmlElement()> _
            Public Property astronomy() As astronomyClass
                Get
                    Return _astronomy
                End Get
                Set(ByVal value As astronomyClass)
                    _astronomy = value
                End Set
            End Property
            Private _image As imageClass
            ''' <summary>
            '''  The image used to identify this feed
            ''' </summary>
            <XmlElement()> _
            Public Property image() As imageClass
                Get
                    Return _image
                End Get
                Set(ByVal value As imageClass)
                    _image = value
                End Set
            End Property
            Private _item As itemClass
            ''' <summary>
            '''  The local weather conditions and forecast for a specific location.
            ''' </summary>
            <XmlElement()> _
            Public Property item() As itemClass
                Get
                    Return _item
                End Get
                Set(ByVal value As itemClass)
                    _item = value
                End Set
            End Property
        End Class
    End Class
End Class
 
 
在chanel中声明了他包含哪些子节点,同样我们也需要为这些子节点申明对象。
Imports Microsoft.VisualBasic
Imports System.Xml.Serialization
Partial Class YahooWeatherForecast
    Partial Class rssClass
        Partial Class channelClass
            Public Class atmosphereClass
                Private _humidity As Integer
                ''' <summary>
                '''  humidity, in percent
                ''' </summary>
                <XmlAttribute()> _
                Public Property humidity() As Integer
                    Get
                        Return _humidity
                    End Get
                    Set(ByVal value As Integer)
                        _humidity = value
                    End Set
                End Property
                Private _visibility As Double
                ''' <summary>
                '''   in the units specified by the distance attribute of the units element (mi or km). Note that the visibility is specified as the actual value * 100. For example, a visibility of 16.5 miles will be specified as 1650. A visibility of 14 kilometers will appear as 1400.
                ''' </summary>
                <XmlAttribute()> _
                Public Property visibility() As Double
                    Get
                        Return _visibility
                    End Get
                    Set(ByVal value As Double)
                        _visibility = value
                    End Set
                End Property
 
                Private _pressure As Double
                ''' <summary>
                '''  barometric pressure, in the units specified by the pressure attribute of the units element (in or mb).
                ''' </summary>
                <XmlAttribute()> _
                Public Property pressure() As Double
                    Get
                        Return _pressure
                    End Get
                    Set(ByVal value As Double)
                        _pressure = value
                    End Set
                End Property
 
 
                Private _rising As Integer
                ''' <summary>
                '''  state of the barometric pressure,   steady = 0, rising = 1, falling = 2
                ''' </summary>
                <XmlAttribute()> _
                Public Property rising() As Integer
                    Get
                        Return _rising
                    End Get
                    Set(ByVal value As Integer)
                        _rising = value
                    End Set
                End Property
            End Class
        End Class
    End Class
End Class
 
在申明完对象之后,我们就可以将xml文件转换为相应的对象。
代码如下:
      Dim doc As New System.Xml.XmlDocument()
        Dim str As String = "http://xml.weather.yahoo.com/forecastrss?p=" & p & "&u=" & U
        Dim c As rssClass
        'Load data  
        doc.Load(str)
        str = doc.OuterXml
 
 
        'XmlSerializer could not Serialize XML with this Elements so i just replace them with Null String!
        str = str.Replace("yweather:", "")
        str = str.Replace("geo:", "")
        'Dim str1 As String = """  : "
 
        Dim str1 = "isPermaLink=""false"""
        str = str.Replace(str1, "")
        str1 = " version=""2.0"" xmlns:yweather=""http://xml.weather.yahoo.com/ns/rss/1.0"" xmlns:geo=""http://www.w3.org/2003/01/geo/wgs84_pos#"""
        str = str.Replace(str1, "")
        Dim memoryStream As New IO.MemoryStream()
        Dim d As New IO.StringReader(str)
 
        Dim xs As New XmlSerializer(GetType(rssClass))
 
        c = CType(xs.Deserialize(d), rssClass)
 
        rss = c
 
 
最后用户可以根据自己的需要将对象中的属性取出,使用于相关的应用中。类似如下代码
       Dim t As New YahooWeatherLib.YahooWeatherForecast("CHXX0044", "f")
        Label1.Text = t.rss.channel.item.forecast.high
        Label2.Text = t.rss.channel.item.forecast.low
        Label5.Text = t.rss.channel.item.title


本文转自elbertchen 51CTO博客,原文链接:http://blog.51cto.com/linkyou/282659,如需转载请自行联系原作者