Go xml unmarshal不起作用,除非我删除前面的xml version =“1.0”encoding =“ISO-8859-1”

时间:2015-11-19 06:59:34

标签: xml go unmarshalling

我已经花了几个小时试图解决这个问题,但我不明白为什么这不会返回任何东西,只是一个空字符串。如果我将响应主体剪切并粘贴到变量并删除?xml version =“1.0”encoding =“ISO-8859-1”?它工作正常。

package main

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

type entry struct {
    XMLName  xml.Name `xml:"entry"`
    Title    string   `xml:"title"`
    Link     string   `xml:"link"`
    Summary  string   `xml:"summary"`
    Updated  string   `xml:"updated"`
    Catagory string   `xml:"catagory"`
    ID       string   `xml:"id"`
}

type Feed struct {
    XMLName xml.Name `xml:"feed"`
    Title   string   `xml:"title"`
    Entry   []entry  `xml:"entry"`
}

func main() {
    resp, err := http.Get("https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&type=4&company=&dateb=&owner=include&start=0&count=2&output=atom")
    if err != nil {
        fmt.Println("Get sec main xml error: %s", err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    //fmt.Println(string(body))
    var feedData Feed
    xml.Unmarshal(body, &feedData)

    fmt.Println(feedData.Title)

    for _, entry := range feedData.Entry {
        fmt.Println(entry.ID)
    }
}

谁能看到我犯错误的地方?感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

来自codefreak提供的链接答案是由moraes在"更新了2015年的答案&超出" 更新了工作代码:

package main

import (
    "encoding/xml"
    "fmt"
    "golang.org/x/net/html/charset"
    "net/http"
)

type entry struct {
    XMLName  xml.Name `xml:"entry"`
    Title    string   `xml:"title"`
    Link     string   `xml:"link"`
    Summary  string   `xml:"summary"`
    Updated  string   `xml:"updated"`
    Catagory string   `xml:"catagory"`
    ID       string   `xml:"id"`
}

type Feed struct {
    XMLName xml.Name `xml:"feed"`
    Title   string   `xml:"title"`
    Entry   []entry  `xml:"entry"`
}

func main() {
    resp, err := http.Get("https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&type=4&company=&dateb=&owner=include&start=0&count=2&output=atom")
    if err != nil {
        fmt.Println("Get sec main xml error: %s", err)
    }
    defer resp.Body.Close()
    var feedData Feed
    decoder := xml.NewDecoder(resp.Body)
    decoder.CharsetReader = charset.NewReaderLabel
    err = decoder.Decode(&feedData)

    fmt.Println(feedData.Title)

    for _, entry := range feedData.Entry {
        fmt.Println(entry.ID)
    }
}

谢谢!