0

我正在从 Web 检索一些 XML,但在提取所需数据时遇到问题。这是 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>

我想提取姓名、性别和国家。这是代码:

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"`
}

但每次我运行这个我总是得到这个:

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

有人能指出问题出在哪里吗?
谢谢。

4

1 回答 1

4

好的,问题是,您没有充分描述xml要解组的数据。您的数据看起来更像

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

像这样的东西应该工作。基本上Unmarshal就是只看顶层节点,而不是往下走找结构。

于 2013-04-13T20:04:33.770 回答