如何在go语言中使用编码/ xml包获取xml属性值



我需要将以下xml转换为go结构。

https://play.golang.org/p/tboi-mp06k

var data = `<Message xmlns="http://www.ncpdp.org/schema/SCRIPT"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     release="006"
     version="010">`
type Message struct {
   XMLName  xml.Name `xml:http://www.ncpdp.org/schema/SCRIPT "Message"`
   release string `xml:"release,attr"`
   version string `xml:"version,attr"`
}
func main() {
    msg := Message{}
    _ = xml.Unmarshal([]byte(data), &msg)   
   fmt.Printf("%#vn", msg)

}

程序输出以下内容:主要。Message{XMLName:xml.Name{Space:"http://www.ncpdp.org/schema/SCRIPT", Local:"Message"}, release:", version:"}版本和版本为空。有什么建议吗?

将结构更改为:

type Message struct {
   XMLName  xml.Name `xml:http://www.ncpdp.org/schema/SCRIPT "Message"`
   Release string `xml:"release,attr"`
   Version string `xml:"version,attr"`
}

将解决问题。Go 使用案例来确定特定标识符在包的上下文中是公共的还是私有的。在代码中,xml.Unmarshal看不到这些字段,因为它不是包含代码的包的一部分。

当您将字段

更改为大写时,它们将变为公共字段,因此可以导出。

工作实例 : https://play.golang.org/p/h8Q4t_3ctS

最新更新