doutu7123 2013-04-13 18:37
浏览 37
已采纳

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

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
", 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条回答 默认 最新

  • douzhiji2020 2013-04-13 20:04
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误