golang XML不是unmarshaling

时间:2013-07-23 20:22:35

标签: xml go

我有以下XML:

<wb:sources page="1" pages="1" per_page="50" total="28" xmlns:wb="http://www.worldbank.org">
  <wb:source id="11">
    <wb:name>Africa Development Indicators</wb:name>
    <wb:description />
    <wb:url />
  </wb:source>
  <wb:source id="31">
    <wb:name>Country Policy and Institutional Assessment (CPIA) </wb:name>
    <wb:description />
    <wb:url />
  </wb:source>
</wb:sources>

我解析XML的代码:

     type Source struct {
    Id   string `xml:"id,attr"`
    Name string `xml"wb:name"`
}

type Sources struct {
    XMLName xml.Name `xml"wb:sources"`
    Sourcez []Source `xml"wb:source"`
}

    func GetSources() (*Sources, error) {
        resp, err := http.Get(sourcesUrl)
        if err != nil {
            log.Fatalf("error %v", err)
            return nil, err
        }

        defer resp.Body.Close()
        s := new(Sources)
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Print(err)
            return nil, err
        }
        log.Printf("body %v", string(body))

        xml.Unmarshal(body, &s)
        return s, nil

    }

My code:

    sources, err := GetSources()
        if err != nil {
            log.Panic()
        }

        fmt.Printf("%v ", sources)

继续回复&{{http://www.worldbank.org sources} []}我做错了什么?

2 个答案:

答案 0 :(得分:3)

您不应在结构中使用wb:

以下是您的示例简化和工作: http://play.golang.org/p/fphHokLprT

答案 1 :(得分:0)

将结构更改为:

type Source struct {
    Name        string `xml:"name"`
    Description string `xml:"description"`
    Url         string `xml:"url"`
}

type Sources struct {
    XMLName    xml.Name `xml"sources"`
    SourceList []Source `xml:"source"`
}

它有效!!