无法从GO中的XML中提取正确的数据

huangapple go评论117阅读模式
英文:

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:

  1. <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">
  2. <artist-list count="2" offset="0">
  3. <artist id="35dac7d2-0b1f-470f-9a5a-c53c8821f6d6" type="Person" ext:score="100">
  4. <name>Eric Prydz</name>
  5. <sort-name>Prydz, Eric</sort-name>
  6. <gender>male</gender>
  7. <country>SE</country>
  8. </artist>
  9. </artist-list>
  10. </metadata>

I want to extract the name, gender and country. This is the code:

  1. package main
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. func main() {
  9. client := &http.Client{}
  10. req, _ := http.NewRequest("GET", "http://www.musicbrainz.org/ws/2/artist/?query=artist:Fred", nil)
  11. res, _ := client.Do(req)
  12. bs, _ := ioutil.ReadAll(res.Body)
  13. var artist Artist
  14. xml.Unmarshal(bs, &artist)
  15. fmt.Printf("%#v\n", artist)
  16. }
  17. type Artist struct {
  18. Name string `xml: "name"`
  19. Gender string `xml: "gender"`
  20. Country string `xml: "country"`
  21. }

But everytime I run this I always get this:

  1. main.Artist{Name:"", Gender:"", Country:""}

Can someone point where the problem is ?
Thanks.

答案1

得分: 4

好的,问题是,你没有充分描述xml的数据以进行解组。你的数据看起来更像是:

  1. struct metadata {
  2. // 你需要给它加上标签,因为Go的字段名不能包含-符号
  3. artists []Artist "artist-list"
  4. }

这样应该可以工作。基本上,Unmarshal只会查看顶级节点,而不会向下查找结构。

英文:

Okay, the problem is, you haven't adequately described the data for xml to unmarshal. Your data looks more like

  1. struct metadata {
  2. // you need to tag it because go field names can't contain -'s
  3. artists []Artist "artist-list"
  4. }

Something like that should work. Basically, Unmarshal is only going to look at the top-level nodes, not walk down looking for a structure.

huangapple
  • 本文由 发表于 2013年4月14日 02:37:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/15991443.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定