dougu4704 2013-02-13 14:34
浏览 59
已采纳

使用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)}}
  • 写回答

1条回答 默认 最新

  • douye4254 2013-02-13 14:57
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制