使用Go解析xml,其中包含多个项目

I just can't get this simple thing to work. I'm just trying to parse a simple RSS XML and put all the items in an array of structs.

this is my code:

package main 

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "encoding/xml"
)

type RSS struct {
    XMLName xml.Name `xml:"rss"`
    items Items `xml:"channel"`
}
type Items struct {
    XMLName xml.Name `xml:"channel"`
    ItemList []Item `xml:"item"`
}
type Item struct {
    title string `xml:"title"`
    link string
    description string
}

func main() {
    res, err := http.Get("http://news.google.com/news?hl=en&gl=us&q=samsung&um=1&ie=UTF-8&output=rss")
    if err != nil {
        log.Fatal(err)
    }
    asText, err := ioutil.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    var i RSS
    err = xml.Unmarshal([]byte(asText), &i)
    if err != nil {
        log.Fatal(err)  
    }

//  fmt.Printf("\ttxt2: %s
", asText)
    fmt.Printf("%#v", i)

    for c, item := range i.items.ItemList {
        fmt.Printf("\t%d: %s
", c, item.title)
    }

    res.Body.Close()

}

this is the output of dumping i:

main.RSS{XMLName:xml.Name{Space:"", Local:"rss"}, items:main.Items{XMLName:xml.Name{Space:"", Local:""}, ItemList:[]main.Item(nil)}}

From the docs of Unmarshal:

Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.

So you need to upper-case your struct field names. Unfortunately, then they don't match the XML element names anymore, so you'll have to repeat their lower-case versions.

Here's a working example with the first two items of your RSS feed: http://play.golang.org/p/jIV_DoCEfq