Go XML Unmarshal example doesn't compile
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>gre@example.com</addr>
</email>
<email where='work'>
<addr>gre@work.com</addr&g开发者_JS百科t;
</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 )
}
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}
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.
It also works if you supply xml.Name{} along with the other arguments, like so:
var result = Result{ xml.Name{"", "result"}, "name", "phone", nil }
Here
var result Result
works.
精彩评论