dpwdsmbvm496180204 2014-05-18 17:04
浏览 157
已采纳

Golang:解组自动关闭标签

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)
  • 写回答

4条回答 默认 最新

  • drvntaomy06331839 2014-05-18 17:46
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?