2016-01-24 229 views
0

我正在嘗試在Go中編寫播客下載程序。以下代碼解析RSS提要,但將解析的數據打印到標準輸出時,通道的鏈接爲空。我不知道爲什麼。有什麼建議麼?我是Go新手。在Go中解析RSS提要

package main 

import (
    "encoding/xml" 
    "fmt" 
    "net/http" 
) 

type Enclosure struct { 
    Url string `xml:"url,attr"` 
    Length int64 `xml:"length,attr"` 
    Type string `xml:"type,attr"` 
} 

type Item struct { 
    Title  string `xml:"title"` 
    Link  string `xml:"link"` 
    Desc  string `xml:"description"` 
    Guid  string `xml:"guid"` 
    Enclosure Enclosure `xml:"enclosure"` 
    PubDate string `xml:"pubDate"` 
} 

type Channel struct { 
    Title string `xml:"title"` 
    Link string `xml:"link"` 
    Desc string `xml:"description"` 
    Items []Item `xml:"item"` 
} 

type Rss struct { 
    Channel Channel `xml:"channel"` 
} 

func main() { 
    resp, err := http.Get("http://www.bbc.co.uk/programmes/p02nrvz8/episodes/downloads.rss") 
    if err != nil { 
     fmt.Printf("Error GET: %v\n", err) 
     return 
    } 
    defer resp.Body.Close() 

    rss := Rss{} 

    decoder := xml.NewDecoder(resp.Body) 
    err = decoder.Decode(&rss) 
    if err != nil { 
     fmt.Printf("Error Decode: %v\n", err) 
     return 
    } 

    fmt.Printf("Channel title: %v\n", rss.Channel.Title) 
    fmt.Printf("Channel link: %v\n", rss.Channel.Link) 

    for i, item := range rss.Channel.Items { 
     fmt.Printf("%v. item title: %v\n", i, item.Title) 
    } 
} 

回答

4

rss feed中的xml有一個帶有兩個子元素'link'元素的通道元素:'link'和'atom:link'。即使有一個名稱空間前綴,Go xml unmarshaller也會發現衝突。另見local name collisions failissue on github

<?xml version="1.0" encoding="UTF-8"?> 
... 
    <channel> 
     <title>Forum - Sixty Second Idea to Improve the World</title> 
     <link>http://www.bbc.co.uk/programmes/p02nrvz8</link> 
     ... 
     <atom:link href="http://www.bbc.co.uk/..." />