Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Unmarshal Self Closing Tags

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)
like image 836
Dekker1 Avatar asked May 18 '14 17:05

Dekker1


1 Answers

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
}
like image 140
nemo Avatar answered Sep 17 '22 23:09

nemo