Go - 如何使用切片将 XML 取消封送到容器结构中



我有一个XML结构,本质上包括一个节点数组,这些节点应该反序列化为一个简单的go结构的一部分,但它不起作用。这是我正在使用的代码(注释显示了我的期望):

package main
import "fmt"
import "encoding/xml"
func main() {
    c := Conversation{}
    xml.Unmarshal(raw, &c)
    fmt.Println(len(c.Dialog))    // expecting 2, not 0
    fmt.Println(c.Dialog[0].Text) // expecting "Hi", not a panic
}
var raw = []byte(`<conversation>
    <message>
        <text>Hi</text>
    </message>
    <message>
        <text>Bye</text>
    </message>
</conversation>`)
type Conversation struct {
    Dialog []Message `xml:"conversation"`
}
type Message struct {
    XMLName xml.Name `xml:"message"`
    Text    string   `xml:"text"`
}

为什么这不起作用?

游乐场:http://play.golang.org/p/a_d-nhcfoP

问题是您的结构字段标记是错误的Conversation.Dialog。标签应该说"message",而不是"conversation"

type Conversation struct {
    Dialog []Message `xml: "message"`
}

http://play.golang.org/p/5VPUcHRLbe

最新更新