我无法让这个简单的事情发挥作用.我只是想解析一个简单的RSS XML并将所有项放在一个结构数组中. 这是我的代码: package main import ( "fmt" "io/ioutil" "log" "net/http" "encoding/xml")type RSS struct
这是我的代码:
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\n", asText) fmt.Printf("%#v", i) for c, item := range i.items.ItemList { fmt.Printf("\t%d: %s\n", c, item.title) } res.Body.Close() }
这是倾销i的输出:
main.RSS{XMLName:xml.Name{Space:"", Local:"rss"}, items:main.Items{XMLName:xml.Name{Space:"", Local:""}, ItemList:[]main.Item(nil)}}来自 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.
因此,您需要大写结构字段名称.不幸的是,它们不再与XML元素名称匹配,因此您必须重复它们的小写版本.
以下是RSS源的前两项的工作示例:http://play.golang.org/p/jIV_DoCEfq