英文:
Go - How to unmarshal XML into container struct with a slice
问题
我有一个XML结构,基本上包含一个节点数组,应该反序列化为一个简单的Go结构的切片,但它没有起作用。以下是我正在使用的代码(注释显示了我的期望):
package main
import "fmt"
import "encoding/xml"
func main() {
c := Conversation{}
xml.Unmarshal(raw, &c)
fmt.Println(len(c.Dialog)) // 期望输出2,而不是0
fmt.Println(c.Dialog[0].Text) // 期望输出"Hi",而不是发生错误
}
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"`
}
为什么这个代码没有起作用?
Playground: http://play.golang.org/p/a_d-nhcfoP
英文:
I have an XML structure that essentially, includes an array of nodes that should deserialize into a slice of a simple go struct but it's not working. Here's the code I'm working with (the comments show what I expect):
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"`
}
Why isn't this working?
Playground: http://play.golang.org/p/a_d-nhcfoP
答案1
得分: 4
问题在于你的Conversation.Dialog
结构字段标签是错误的。标签应该是"message"
,而不是"conversation"
:
type Conversation struct {
Dialog []Message `xml:"message"`
}
http://play.golang.org/p/5VPUcHRLbe
英文:
The issue is that your struct field tag for Conversation.Dialog
is wrong. The tag should say "message"
, not "conversation"
:
type Conversation struct {
Dialog []Message `xml: "message"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论