dongshan3759 2016-01-24 12:33
浏览 70
已采纳

在Go中解析RSS feed

I am trying to write a podcast downloader in Go. The following code parses an RSS feed but the link of the channel is empty when printing the parsed data to the standard output. I don't know why. Any suggestions? I am new to Go.

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
", 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
", err)
        return
    }

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

    for i, item := range rss.Channel.Items {
        fmt.Printf("%v. item title: %v
", i, item.Title)
    }
}
  • 写回答

1条回答 默认 最新

  • dongzai0020 2016-01-24 15:35
    关注

    The xml from the rss feed has a channel element with two child 'link' elements: 'link' and 'atom:link'. Even though one has a namespace prefix, Go xml unmarshaller sees a conflict. See also local name collisions fail and issue 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/..." />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来