首先,由于要处理XML,读取网站上的资源,所以要引入如下几个命名空间
Imports System.Net
Imports System.IO
Imports System.Xml |
当用户点选某个分类主题的按钮时,将会自动下载该网站中符合主题的RSS XML文件,下载完后再进行解析,再显示到页面中去。代码如下:
Public Function SendRequest( _
ByVal URI As String, _
ByVal requestType As String) As HttpWebRequest
Dim req As HttpWebRequest = Nothing
Try
//发起HTTP请求
req = HttpWebRequest.Create(URI)
req.Method = requestType
Catch ex As Exception
Throw New Exception("Error")
End Try
Return req
End Function
Public Function GetResponse( _
ByVal req As HttpWebRequest) As String
Dim body As String = String.Empty
Try
//从服务器中获得响应输出流
Dim resp As HttpWebResponse = req.GetResponse()
Dim stream As Stream = resp.GetResponseStream()
//使用streamreader去处理得到的服务器响应
Dim reader As StreamReader = _
New StreamReader(stream, Encoding.UTF8)
body = reader.ReadToEnd()
stream.Close()
Catch ex As Exception
Throw New Exception("Error")
End Try
Return body
End Function |
上面的两个方法,分别向网站服务器发出获取指定URL的信息的请求,并用IO流中的streamreader的方式获得服务器返回的输出信息。而下面的LoadRSS()方法,传入的参数是指定的URL地址,然后分别调用上面的两个方法,在最后获得服务器返回的输出流后,再通过解析XML的方式,选择合适的结点内容进行返回。代码如下:
Public Function LoadRSS( _
ByVal URI As String) As String
Dim req As HttpWebRequest
Dim xmlDoc As XmlDocument = Nothing
Try
XmlDataSource1.DataFile = URI
//下载RSS XML文件
req = SendRequest(URI, "GET")
Dim xmlData As String = GetResponse(req)
xmlDoc = New XmlDocument()
xmlDoc.LoadXml(xmlData)
//选择合适的结点
Dim titleNode As XmlNode = _
xmlDoc.DocumentElement.SelectSingleNode("channel/title")
Return titleNode.InnerText
Catch ex As Exception
Return String.Empty
End Try
End Function |