So I'm trying to Unmarshal an XML file generated as a save file by another program in Google Go. It seems to be going great as the documentation on this is quite extensive: http://golang.org/pkg/encoding/xml/#Unmarshal
Still I'm running into a problem. The output in the save file is like this:
<location id="id4" x="-736" y="-544">
<committed />
</location>
Instead of committed, a location can also be urgent or neither. The locations can also have a name and different labels, but these seem to be parsing just fine. In my Go code I'm using the following struct:
type Location struct {
Id string `xml:"id,attr"`
Committed bool `xml:"commited"`
Urgent bool `xml:"urgent"`
Labels []Label `xml:"label"`
}
And although the Unmarshal function of the encoding/xml package runs without errors and the shown example is present in the data, all the values of both committed and urgent are "false".
What should I change to get the right values for these two fields?
(Unmarshalling is done using the following piece of code)
xmlFile, err := os.Open("model.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
b, _ := ioutil.ReadAll(xmlFile)
var xmlScheme uppaal.UppaalXML
err = xml.Unmarshal(b, &xmlScheme)
fmt.Println(err)
According to this discussion this behaviour is not supported and the only reason you don't see an error is that you mispelled committed
in the struct definition. If you write it correctly you will get a parse error because an empty string (the contents of a closed tag) is not a boolean value (example on play).
In the linked golang-nuts thread rsc suggests to use *struct{}
(a pointer to an empty struct) and check if that value is nil
(example on play):
type Location struct {
Id string `xml:"id,attr"`
Committed *struct{} `xml:"committed"`
Urgent bool `xml:"urgent"`
}
if l.Committed != nil {
// handle not committed
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With