tags:

views:

172

answers:

4

The Xml example in the go docs is broken. Does anyone know how to make it work? When I compile it, the result is:

xmlexample.go:34: cannot use "name" (type string) as type xml.Name in field value
xmlexample.go:34: cannot use nil as type string in field value
xmlexample.go:34: too few values in struct initializer

Here is the relevant code:

package main

import (
        "bytes"
        "xml"
)

type Email struct {
        Where string "attr";
        Addr string;
}

type Result struct {
        XMLName xml.Name "result";
        Name string;
        Phone string;
        Email []Email;
}

var buf = bytes.NewBufferString ( `
<result>
        <email where="home">
                <addr>[email protected]</addr>
        </email>
        <email where='work'>
                <addr>[email protected]</addr>
        </email>
        <name>Grace R. Emlin</name>
        <address>123 Main Street</address>
</result>`)


func main() {
        var result = Result{ "name", "phone", nil }
        xml.Unmarshal ( buf , &result )
        println ( result.Name )
}
+3  A: 

The line

var result = Result{ "name", "phone", nil }

needs to become

var result = Result{ Name: "name", Phone: "phone", Email: nil }

Then it should work as expected. I submitted a patch to fix the documentation and by coincidence a release occurred soon after, so no one should run into this particular issue again.

Evan Shaw
thanks for sending the patch
marketer
+1  A: 

It also works if you supply xml.Name{} along with the other arguments, like so:

var result = Result{ xml.Name{"", "result"}, "name", "phone", nil }
AlexCombas
+2  A: 

The type Result is defined as:

type Result struct {
    XMLName xml.Name "result"
    Name    string
    Phone   string
    Email   []Email
}

The type xml.Name, embedded in type Result, is defined as:

// A Name represents an XML name (Local) annotated
// with a name space identifier (Space).
// In tokens returned by Parser.Token, the Space identifier
// is given as a canonical URL, not the short prefix used
// in the document being parsed.
type Name struct {
    Space, Local string
}

Therefore, initialize, using composite literals, using something similar to one of:

var result = Result{xml.Name{}, "name", "phone", nil}

var result = Result{xml.Name{"space", "local"}, "name", "phone", nil}

var result = Result{Name: "name", Phone: "phone", Email: nil}
peterSO
A: 

Here

var result Result

works.

Kinopiko