Go XML Unmarshal esempio non può essere compilato
Domanda
L'esempio Xml nel rel="nofollow andare docs è rotto. Qualcuno sa come farlo funzionare? Quando compilo, il risultato è il seguente:
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
Ecco il codice corrispondente:
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>
</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 )
}
Soluzione
Il type Result
è definito come:
type Result struct {
XMLName xml.Name "result"
Name string
Phone string
Email []Email
}
Il type xml.Name
, incorporato in type Result
, è definito come:
// 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
}
Quindi, l'inizializzazione, utilizzando letterali compositi, usando qualcosa di simile a uno dei seguenti:
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}
Altri suggerimenti
La linea
var result = Result{ "name", "phone", nil }
ha la necessità di diventare
var result = Result{ Name: "name", Phone: "phone", Email: nil }
Quindi dovrebbe funzionare come previsto. Ho presentato una patch per correggere la documentazione e per coincidenza un liberazione è avvenuta subito dopo, in modo che nessuno dovrebbe incorrere in questo particolare problema di nuovo.
Funziona anche se si fornisce xml.Name {} insieme ad altri argomenti, in questo modo:
var result = Result{ xml.Name{"", "result"}, "name", "phone", nil }
Qui
var result Result
opere.