Go – 如何将XML解组为带有切片的容器结构体

huangapple go评论79阅读模式
英文:

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 &quot;fmt&quot;
import &quot;encoding/xml&quot;

func main() {
    c := Conversation{}
    xml.Unmarshal(raw, &amp;c)
    fmt.Println(len(c.Dialog))    // expecting 2, not 0
    fmt.Println(c.Dialog[0].Text) // expecting &quot;Hi&quot;, not a panic
}

var raw = []byte(`&lt;conversation&gt;
    &lt;message&gt;
        &lt;text&gt;Hi&lt;/text&gt;
    &lt;/message&gt;
    &lt;message&gt;
        &lt;text&gt;Bye&lt;/text&gt;
    &lt;/message&gt;
&lt;/conversation&gt;`)

type Conversation struct {
    Dialog []Message `xml:&quot;conversation&quot;`
}

type Message struct {
    XMLName xml.Name `xml:&quot;message&quot;`
    Text    string   `xml:&quot;text&quot;`
}

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 &quot;message&quot;, not &quot;conversation&quot;:

type Conversation struct {
    Dialog []Message `xml: &quot;message&quot;`
}

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

huangapple
  • 本文由 发表于 2014年1月15日 06:38:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/21125523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定