您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用Golang解码Reddit的RSS?

如何使用Golang解码Reddit的RSS?

您的程序接近完成,但是需要指定更多上下文来匹配XML文档。

您需要修改字段标签,以帮助指导XML绑定贯穿您的 Channel结构到您的Item结构:

type Channel struct {
    Items []Item `xml:"channel>item"`
}

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

根据的文档encoding/xml.Unmarshal(),第七项在此处适用:

如果XML元素包含名称与格式为“ a”或“ a> b> c”的标记的前缀匹配的子元素,则unmarshal将下降到XML结构中以查找具有给定名称的元素,并将其映射该结构字段的最里面的元素。以“>”开头的标记等效于以字段名称后跟“>”开头的标记

在您的情况下,您希望遍历顶级<RSS>元素的<channel>元素以找到每个<item>元素。但是请注意,我们不需要(实际上不需要)通过将字段的标签写为Channel来指定结构应钻入顶层<RSS>元素Items

`xml:"RSS>channel>item"`

该上下文是隐式的;提供的结构Unmarshall()已经映射到顶级XML元素。

还要注意,您的Channel结构的Items字段应该是slice-of-类型的Item,而不仅仅是single Item

您提到您在使提案生效方面遇到困难。这是一份完整的清单,我发现可以正常使用:

package main

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

type Channel struct {
    Items []Item `xml:"channel>item"`
}

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

func main() {
    if res, err := http.Get("http://www.reddit.com/r/google.xml"); err != nil {
        fmt.Println("Error retrieving resource:", err)
        os.Exit(1)
    } else {
        channel := Channel{}
        if err := xml.NewDecoder(res.Body).Decode(&channel); err != nil {
            fmt.Println("Error:", err)
            os.Exit(1)
        } else if len(channel.Items) != 0 {
            item := channel.Items[0]
            fmt.Println("First title:", item.Title)
            fmt.Println("First link:", item.Link)
            fmt.Println("First description:", item.Description)
        }
    }
}
Go 2022/1/1 18:13:47 有447人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶