gpt4 book ai didi

xml - 在 Go 中解析 RSS 提要

转载 作者:IT王子 更新时间:2023-10-29 02:29:51 26 4
gpt4 key购买 nike

我正在尝试用 Go 编写播客下载器。以下代码解析 RSS 提要,但在将解析数据打印到标准输出时 channel 链接为空。我不知道为什么。有什么建议么?我是 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\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)
}
}

最佳答案

来自 rss 提要的 xml 有一个带有两个子“link”元素的 channel 元素:“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/..." />

关于xml - 在 Go 中解析 RSS 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34975837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com