您的程序接近完成,但是需要指定更多上下文来匹配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 mainimport ( "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.NewDeprer(res.Body).Depre(&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) } }}


