dongyang7152 2014-01-14 14:38
浏览 33
已采纳

Go-如何使用切片将XML解组到容器结构中

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条回答 默认 最新

  • dousong2967 2014-01-14 14:42
    关注

    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"`
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部