英文:
Cannot extract correct data from XML in GO
问题
type Artist struct {
Name string xml:"name"
Gender string xml:"gender"
Country string xml:"country"
}
英文:
I am retrieving some XML from the web, but I am having problem extracting the data that I need. This is the XML:
<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#" xmlns:ext="http://musicbrainz.org/ns/ext#-2.0" created="2013-04-13T16:54:01.107Z">
<artist-list count="2" offset="0">
<artist id="35dac7d2-0b1f-470f-9a5a-c53c8821f6d6" type="Person" ext:score="100">
<name>Eric Prydz</name>
<sort-name>Prydz, Eric</sort-name>
<gender>male</gender>
<country>SE</country>
</artist>
</artist-list>
</metadata>
I want to extract the name, gender and country. This is the code:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
client := &http.Client{}
req, _ := http.NewRequest("GET", "http://www.musicbrainz.org/ws/2/artist/?query=artist:Fred", nil)
res, _ := client.Do(req)
bs, _ := ioutil.ReadAll(res.Body)
var artist Artist
xml.Unmarshal(bs, &artist)
fmt.Printf("%#v\n", artist)
}
type Artist struct {
Name string `xml: "name"`
Gender string `xml: "gender"`
Country string `xml: "country"`
}
But everytime I run this I always get this:
main.Artist{Name:"", Gender:"", Country:""}
Can someone point where the problem is ?
Thanks.
答案1
得分: 4
好的,问题是,你没有充分描述xml
的数据以进行解组。你的数据看起来更像是:
struct metadata {
// 你需要给它加上标签,因为Go的字段名不能包含-符号
artists []Artist "artist-list"
}
这样应该可以工作。基本上,Unmarshal
只会查看顶级节点,而不会向下查找结构。
英文:
Okay, the problem is, you haven't adequately described the data for xml
to unmarshal. Your data looks more like
struct metadata {
// you need to tag it because go field names can't contain -'s
artists []Artist "artist-list"
}
Something like that should work. Basically, Unmarshal
is only going to look at the top-level nodes, not walk down looking for a structure.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论