0

我有以下 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} []}我做错了什么?

4

2 回答 2

3

您不应该wb:在结构中使用。

这是您的示例简化且有效: http ://play.golang.org/p/fphHokLprT

于 2013-07-23T21:06:51.650 回答
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"`
}

它奏效了!!

于 2013-07-23T21:05:29.510 回答