Golang:Unmarshal Self Closing Tags

Dek*_*er1 5 xml go unmarshalling

因此,我正在尝试解组由Google Go中的另一个程序生成的保存文件生成的XML文件.它似乎很好,因为关于这方面的文档相当广泛:http://golang.org/pkg/encoding/xml/#Unmarshal

我还在遇到问题.保存文件中的输出如下:

<location id="id4" x="-736" y="-544">
    <committed />
</location>
Run Code Online (Sandbox Code Playgroud)

而不是承诺,一个位置也可能是紧急的或两者都不是.这些位置也可以有一个名称和不同的标签,但这些似乎解析得很好.在我的Go代码中,我使用以下结构:

type Location struct {
    Id string `xml:"id,attr"`
    Committed bool `xml:"commited"`
    Urgent bool `xml:"urgent"`
    Labels []Label `xml:"label"`
}
Run Code Online (Sandbox Code Playgroud)

虽然encoding/xml包的Unmarshal函数运行时没有错误,并且数据中显示了所示的示例,但commit和urgent的所有值都是"false".

我应该更改什么才能获得这两个字段的正确值?

(使用以下代码完成解组)

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)
Run Code Online (Sandbox Code Playgroud)

nem*_*emo 11

根据此讨论,不支持此行为,并且您没有看到错误的唯一原因是您committed在结构定义中拼写错误.如果你正确地写它会得到一个解析错误,因为一个空字符串(一个闭合标签的内容)不是一个布尔值(播放时的例子).

在链接的golang-nuts线程中,rsc建议使用*struct{}(指向空结构的指针)并检查该值是否为nil(播放时的示例):

type Location struct {
    Id        string    `xml:"id,attr"`
    Committed *struct{} `xml:"committed"`
    Urgent    bool      `xml:"urgent"`
}

if l.Committed != nil {
    // handle not committed
}
Run Code Online (Sandbox Code Playgroud)