
使用 App Inventor 讀取 XML 網頁資料
今天來介紹,如何透過「網路」元件,讀取中央氣象局的線上公開資料,並將資料逐步拆解。
1. 開啟瀏覽器,搜尋「中央氣象局」,進入氣象局首頁。
首頁 | 交通部中央氣象局 (cwb.gov.tw)
2. 於首頁右上角的「常用服務」選單,點選「RSS」。

3. 選擇你想要的縣市,這裡我選「高雄市」。

進入後會看到的網頁內容如下:

我們要爬取底下「description」標籤裡的資料

並將資料以下面的格式呈現在手機上:

4. 將這個網頁的網址先存在記事本,等等要設定為「網路」元件的網址。
https://www.cwb.gov.tw/rss/forecast/36_02.xml
5. 開啟 App Inventor 新增一個專案「OpenData」,並拖拉一個按鈕、標籤和網路元件至工作面板。

接著開始撰寫程式碼
6. 拖拉一個當按鈕被點選的方塊,方塊裡要設定網路元件的網址,和執行 GET 請求如下:

7. 拖拉當網路元件取得文字的方塊,裡面要先設定標籤為空,再呼叫要傳值的「拆解資料」副程式如下:

拆解資料需要用到以下方塊:

我們先看看不拆解直接顯示的話,會長什麼樣子?
8. 從網路元件拖拉 XML 文字解碼的方塊,右邊放剛剛讀取到的資料,並將解碼方塊給標籤。

接著開始拆解資料
從剛剛的網頁可以看到,整個資料都是包在 rss 的標籤裡 (最外層是 <rss>……</rss>),所以我們可以用找關鍵字的方塊,一層一層慢慢找。
9. 將解碼方塊放到找關鍵字方塊的右邊,查找關鍵字填入字串「rss」。

再來,下一層標籤是「channel」,所以把這整個方塊,再放到找關鍵字方塊的右邊,如下:

10. 接著,我們要找的資料,在「channel」底下的「item」裡,但因為 channel 標籤底下的 item 標籤有兩個,而我們要找的資料在第二個 item 標籤裡,所以當我們執行完找 item 關鍵字的方塊後,還要再用「選擇清單…索引值…」的方塊選擇第二個,如下:

現在可以看看資料長什麼樣子

現在,第二個 item 標籤裡的資料,只剩四個標籤了!分別是 <pubDate>、<title>、<link> 和 <description> 標籤,而我們要找的資料,就在 description 裡面,所以再用一個找關鍵字的方塊就可以了!


那麼這一大串的資料,還能不能再做拆解呢?像是存到變數,然後每一筆資料都是分開的。
當然可以!!
只要用到「分解文字」方塊,就可以做到,看一下現在的每筆資料後面是不是都有一個 <BR> 標籤 (<br> 標籤在 html 是斷行的意思),可以利用這個做拆解。
11. 將剛剛的找關鍵字方塊放到分解文字方塊的右邊,底下再放字串「<BR>」。

12. 拖拉一個清單的迴圈方塊,將分解方塊放在右邊,裡面設定標籤內容,用合併文字方塊,把每次更新的標籤內容累加。

至此,整個 App 已撰寫完成!
這個範例如果只用選擇清單…索引值的方塊,也能達成同樣效果,只是在拆解的過程中很麻煩,需要一個一個察看結果,這邊也附上使用這個方法的程式碼如下:

如果第一種拆解方法,讓妳整體看起來也很吃力的話,可以試著每用一次關鍵字方塊,就存到變數裡,下一個關鍵字方塊,再把變數放到右邊,是一樣的效果,可讀性也會增加 (Maybe……)。
App 完整程式碼:

App Inventor 專案 aia 檔案下載
App 執行範例:
如果覺得文章內容還不錯的話,麻煩請幫我點個讚!感謝
可以多點幾次喔~~
第一次點讚需使用 Google 或 Facebook 帳號註冊


4 則留言
Dick Liu
一樣用App inventr 2 不要層層分析,有沒有更快速的方式,可以取得所要的資料??
JamesBang
使用「在鍵值…找關鍵字」的方塊是最快速的做法
或是把它當成一個字串,直接用分割方塊做切割也可以,我之前寫過一篇 Inventor 跟 YouTube 的文章,其中找圖片的網址就是用這個方法。
你看看你要找的資料前面是什麼字串,把它複製當成分割符號。(複製長度隨意,最好不要有跟其它重複)
做第一次切割後會變成清單,而你要的資料在清單的第二項,這個時候還需要再做一次分割,因為你要的資料後面,還連著一大堆你不要的,所以要再做一次切割,再切割完後你的資料就在第一項。
Dick Liu
謝謝!!
JamesBang
不客氣~~