您的程序接近完成,但是需要指定更多上下文来匹配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)
}
}
}