LoginSignup
26
24

More than 5 years have passed since last update.

GoでXMLをパースする

Posted at

必要に迫られたのでサンプルを書いてみます。
はてなブックマークのテクノロジーカテゴリの人気エントリーのRSSをパースしてみましょう。

標準のencoding/xmlを使います。

xml_parse.go
package main

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

type XML struct {
    Bookmarks []struct {
        Title string `xml:"title"`
        Link  string `xml:"link"`
        Date  string `xml:"date"`
        Count int    `xml:"bookmarkcount"`
    } `xml:"item"`
}

func main() {
    data := httpGet("http://b.hatena.ne.jp/hotentry/it.rss")

    result := XML{}
    err := xml.Unmarshal([]byte(data), &result)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }

    for _, bookmark := range result.Bookmarks {
        datetime, _ := time.Parse(time.RFC3339, bookmark.Date)

        fmt.Printf("%v\n", datetime.Format("2006/01/02 15:04:05"))
        fmt.Printf("%s - %duser\n", bookmark.Title, bookmark.Count)
        fmt.Printf("%v\n", bookmark.Link)
        fmt.Println()
    }
}

func httpGet(url string) string {
    response, _ := http.Get(url)
    body, _ := ioutil.ReadAll(response.Body)
    defer response.Body.Close()
    return string(body)
}

それでは、実行してみましょう

$ go run xml_parse.go

2015/11/03 17:05:18
Microsoft、「OneDrive」の無料容量縮小ヘ “容量無制限”は終了 - ITmedia ニュース - 38user
http://www.itmedia.co.jp/news/articles/1511/03/news033.html

2015/11/03 14:06:00
Microsoft、「OneDrive」のプラン内容の変更を発表 ー 無制限廃止や無料容量の縮小(15GB⇒5GB)など | 気になる、記になる… - 28user
http://taisy0.com/2015/11/03/60454.html

2015/11/03 12:13:58
一眼レフカメラVSスマホのカメラ!あなたはどっち派? - YUチャンネルブログ - 45user
http://yuchanel.hatenablog.com/entry/2015/11/03/%E4%B8%80%E7%9C%BC%E3%83%AC%E3%83%95%E3%82%AB%E3%83%A1%E3%83%A9VS%E3%82%B9%E3%83%9E%E3%83%9B%E3%81%AE%E3%82%AB%E3%83%A1%E3%83%A9%EF%BC%81%E3%81%82%E3%81%AA%E3%81%9F%E3%81%AF%E3%81%A9%E3%81%A3%E3%81%A1

・
・
・

encoding/jsonを使ってJSONをパースする場合とほとんど違いがありませんね。

26
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
24