這個範例主要是示範如何讀取Data.Taipei的公共廁所資料
最近XNA讀到有點累,轉換一下心情來寫寫Silverlight程式,這個範例主要是示範如何讀取Data.Taipei的公共廁所資料。
先新建一個Windows Phone應用程式專案,並在MainPage.xaml中加入一個Button跟一個TextBlock。
接著連到公廁位置查詢網址就可以知道公廁位置的資料結構,包含了公廁名稱、地址、坐標…
所以我們要建立一個DataClass類別當做資料模型用來儲存讀回來的公廁資料,這裡我偷懶一下只建了公廁名稱跟地址當例子。
Public Class DataClass
Private mName As String
Private mAddress As String
Public Property Name As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
Public Property Address As String
Get
Return mAddress
End Get
Set(ByVal value As String)
mAddress = value
End Set
End Property
End Class
再來我們要開始撰寫主要程式碼
在MainPage類別宣告一個WebClient類別變數,用來讀取遠端XML檔。
Partial Public Class MainPage
Inherits PhoneApplicationPage
Dim remoteXml As WebClient
End Class
在New()裡產生WebClient類別的實例,然後加上一個下載完成的事件。
Public Sub New()
InitializeComponent()
remoteXml = New WebClient()
AddHandler remoteXml.DownloadStringCompleted, AddressOf remoteXml_DownloadCompleted
End Sub
在下載完成後分析XML/Atom資料,並存入restrooms這個DataClass資料模型集合裡,最後把所有公廁全部列出在TextBlock裡。
Sub remoteXml_DownloadCompleted(sender As Object, e As DownloadStringCompletedEventArgs)
Dim rawData As New XDocument
rawData = XDocument.Parse(e.Result)
Dim d As XNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices"
Dim m As XNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
Dim restrooms As IEnumerable(Of DataClass)
restrooms = From rest In rawData.Descendants(m + "properties")
Select New DataClass With {.Name = rest.Element(d + "stitle"), .Address = rest.Element(d + "xaddress")}
Dim txt As String = ""
For Each restroom In restrooms
txt += restroom.Name + System.Environment.NewLine
txt += restroom.Address + System.Environment.NewLine
txt += System.Environment.NewLine
Next
TextBlock1.Text = txt
End Sub
在Button_Click事件,我們用輸入公廁資料網址轉成uri類別,並呼叫DownloadStringAsync開始下載XML檔。
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim uri As Uri = New Uri(uri.EscapeUriString("http://taipeicityopendata.cloudapp.net/v1/TaipeiOGDI/EPA01/"))
remoteXml.DownloadStringAsync(uri)
End Sub
程式執行結果如下,按下按鈕後抓回來的資料經過解析後完整成現出來了,希望透過這一個簡單的範例,大家能發揮創意,寫出方便Windows Phone 7使用者的程式。(範例下載)