I need to convert following xml to go struct.
https://play.golang.org/p/tboi-mp06k
var data = `<Message xmlns="http://www.ncpdp.org/schema/SCRIPT"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
release="006"
version="010">`
type Message struct {
XMLName xml.Name `xml:http://www.ncpdp.org/schema/SCRIPT "Message"`
release string `xml:"release,attr"`
version string `xml:"version,attr"`
}
func main() {
msg := Message{}
_ = xml.Unmarshal([]byte(data), &msg)
fmt.Printf("%#v
", msg)
}
Program outputs the following: main.Message{XMLName:xml.Name{Space:"http://www.ncpdp.org/schema/SCRIPT", Local:"Message"}, release:"", version:""} release and version are empty. Any suggestions please?
Changing your struct to:
type Message struct {
XMLName xml.Name `xml:http://www.ncpdp.org/schema/SCRIPT "Message"`
Release string `xml:"release,attr"`
Version string `xml:"version,attr"`
}
will solve the issue. Go uses case to determine whether a particular identifier is public or private within the context of your package. In your code, the fields are not visible to xml.Unmarshal
because it is not part of the package containing your code.
When you change the fields to be upper case, they became public so could be exported.
Working Example : https://play.golang.org/p/h8Q4t_3ctS