Parsing xml with Go having multiple elements

I just can't get this simple job to work. I'm just trying to parse a simple RSS XML and put all the elements into an array of structures.

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\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()

}

      

this is the result of resetting i:

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

      

+3


source to share


1 answer


From the Unmarshal docs :

Since Unmarshal uses the reflection package, it can only assign exported fields (upper case). Unmarshal uses case-matched comparison to match XML element names to tags and structure field names.



So, you need to capitalize on the structure field names. Unfortunately, they no longer match XML element names, so you have to repeat lowercase versions of them.

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

+7


source







All Articles