0

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.

2
  • It would probably be easier to find the problem if you didn't ignore every single error. I suspect xml.Unmarshal is returning an error that will tell you whats up. That and your root tag isn't an artist object, its a metadata object holding a metadata-list. Commented Apr 13, 2013 at 18:49
  • Unmarshall doesn't return any error, already test it for this, but I dont' understand what to do I will parse ok. I guess my problem is I don't know how to corectlly access the nested values Commented Apr 13, 2013 at 18:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.