xml - 如何使用 Golang 解码 Reddit 的 RSS?

标签 xml go rss decode reddit

我一直在研究 Go 的 XML 包,看不出以下代码有什么问题。

package main

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

type Channel struct {
    Items Item
}

type Item struct {
    Title       string `xml:"title"`
    Link        string `xml:"link"`
    Description string `xml:"description"`
}

func main() {

    var items = new(Channel)
    res, err := http.Get("http://www.reddit.com/r/google.xml")

    if err != nil {
        fmt.Printf("Error: %v\n", err)
    } else {
        decoded := xml.NewDecoder(res.Body)

        err = decoded.Decode(items)

        if err != nil {
            fmt.Printf("Error: %v\n", err)
        }

        fmt.Printf("Title: %s\n", items.Items.Title)
    }
}

上面的代码运行没有任何错误并打印到终端:

Title:

该结构似乎是空的,但我不明白为什么它没有填充 XML 数据。

最佳答案

我会像这样完全明确 - 命名所有 XML 部分

See the playground for a full working example

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

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

type Item struct {
    Title       string `xml:"title"`
    Link        string `xml:"link"`
    Description string `xml:"description"`
}

关于xml - 如何使用 Golang 解码 Reddit 的 RSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19081479/

相关文章:

go - 为什么golang自定义错误变量有多种类型

go - 在 golang 中使用 psexec 时缺少标准输出

ios - RSS 提要无法加载

ios - 保存 rss feed/swift2/iOS

android - "How to concisely implement an editable table layout"

c# - 具体解析XML成数组

html - 当 <a> 埋在另一个标签中时,使用 XPath 获取它的文本,例如<强>

go - 如何在本地创建和使用我自己的 golang 包来运行此测试?

ios - 使用 NSXMLParser 只解析前十个帖子,然后分别解析下一批

javascript - 使用 jQuery 更新 XML 字符串