加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – Golang:Unmarshal Self Closing Tags

发布时间:2020-12-16 23:23:41 所属栏目:百科 来源:网络整理
导读:因此,我正在尝试解组由Google Go中的另一个程序生成的保存文件生成的 XML文件.它似乎很好,因为关于这方面的文档相当广泛: http://golang.org/pkg/encoding/xml/#Unmarshal 我还在遇到问题.保存文件中的输出如下: location id="id4" x="-736" y="-544" comm
因此,我正在尝试解组由Google Go中的另一个程序生成的保存文件生成的 XML文件.它似乎很好,因为关于这方面的文档相当广泛: http://golang.org/pkg/encoding/xml/#Unmarshal

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

<location id="id4" x="-736" y="-544">
    <committed />
</location>

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

type Location struct {
    Id string `xml:"id,attr"`
    Committed bool `xml:"commited"`
    Urgent bool `xml:"urgent"`
    Labels []Label `xml:"label"`
}

虽然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)

解决方法

根据 this discussion,不支持此行为,并且您没有看到错误的唯一原因是您在结构定义中错误提交.如果你正确地写它会得到一个解析错误,因为一个空字符串(一个闭合标签的内容)不是一个布尔值( example on play).

在链接的golang-nuts线程中,rsc建议使用* struct {}(指向空结构的指针)并检查该值是否为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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读