2016-06-11 55 views
0

我需要將以下xml轉換爲結構體。如何在go語言中使用encoding/xml包獲取xml屬性值

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("%#v\n", msg) 

}

計劃輸出以下: main.Message {XMLName:xml.Name {空間: 「http://www.ncpdp.org/schema/SCRIPT」 本地: 「消息」},釋放: 「」 ,版本:「」} 版本和版本爲空。有什麼建議嗎?

+1

任何解析(xml或json)僅適用於導出的字段。 「釋放」和「版本」是未導出的,我想這就是爲什麼它們仍然是空的。 – jnmoal

+0

是的,謝謝! – user1848653

回答

0

你的結構變更爲:

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