英文:
golang XML not unmarshal-ing
问题
我有以下的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
}
我的代码:
sources, err := GetSources()
if err != nil {
log.Panic()
}
fmt.Printf("%v ", sources)
一直返回&{{http://www.worldbank.org sources} []}
,我做错了什么?
英文:
I have the following 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>
My code for parsing the 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)
Keep returning &{{http://www.worldbank.org sources} []}
what I'm I doing wrong?
答案1
得分: 3
你不应该在结构体中使用wb:
。
这是你的示例简化并且可运行的代码:
http://play.golang.org/p/fphHokLprT
英文:
You should not use wb:
in the structs.
Here is your example simplified and working:
http://play.golang.org/p/fphHokLprT
答案2
得分: 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"`
}
然后它就可以工作了!
英文:
Changed the structs to:
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"`
}
and it worked!!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论