登录
首页 >  Golang >  Go问答

Go 中使用动态类型(空接口)的 XML Unmarshal

来源:stackoverflow

时间:2024-04-09 09:42:33 205浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Go 中使用动态类型(空接口)的 XML Unmarshal》,聊聊,我们一起来看看吧!

问题内容

我需要解析具有动态元素的 xml 消息,因此我使用了 interface{} 类型的元素在消息结构中表示它。

一旦我知道了这个动态元素的类型(在运行时),我就会初始化一个消息结构,然后尝试解组 xml 消息。然而,动态元素的内容并未被解组。

这是一个 go 演示,其中包含我想要实现的目标,以及注释和实际输出与预期输出:https://play.golang.org/p/ekvetupmvi2

我尝试了几种变体,但无法使解组按预期工作。谁能帮助我理解为什么会出现这种行为以及如何使其发挥作用?提前致谢。

代码(万一 go 演示链接有一天失效):

package main

import "fmt"
import "encoding/xml"

// XML root
type Message struct {
    XMLName   xml.Name  `xml:"message"`
    Operation Operation `xml:"operation"`
}

// An Operation can contain either a Create or an Update element
type Operation struct {
    Create *Create `xml:"create"`
    Update *Update `xml:"update"`
}

// Doesn't matter...
type Create struct{}

// Update contains a Color element or Any other element (we only know its type during runtime)
type Update struct {
    Color *Color `xml:"color"`
    Other Any
}

// Doesn't matter...
type Color struct{}

type Any interface{}

var xmlStr = []byte(`
    
        
            
                1000
            
        
    
`)

func main() {
    // At this point we already know what to expect to receive in Other, so we can declare a struct for its content (Size)
    type Size struct {
        XMLName xml.Name `xml:"size"`
        Width   string   `xml:"width"`
    }

    // Unmarshal
    msg := &Message{
        Operation: Operation{
            Update: &Update{
                Other: &Size{}, // Here I'm setting Other to Size, so I would expect Go to unmarshal the  contents into it
            },
        },
    }
    if err := xml.Unmarshal(xmlStr, msg); err != nil {
        fmt.Println(err)
    }

    // Marshal again
    b, err := xml.MarshalIndent(msg, "", "    ")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("expected:\n\n%s\n\n", xmlStr)
    fmt.Printf("actual:\n\n%s", string(b))
}

解决方案


根据 encoding/xml 包文档:

如果 xml 元素包含未与任何元素匹配的子元素 上述规则和结构体有一个带有标签 ",any", unmarshal 将子元素映射到该结构字段。

对代码进行一个小更新即可使其按预期工作:

xml:",any" 标记添加到您的 other 字段定义中。

为了清理代码,我还会删除 any 类型,您不需要它。您可以将 other 字段定义更改为带有标签 xml:",any"interface{} 类型并完成相同的操作。

像这样:

Other interface{} `xml:",any"`

执行并查看捕获的“1000”。

我建议更新您的问题以直接包含您的代码,以便人们更轻松地查找/搜索/阅读您的问题。拥有 go 演示链接也很有用,这样读者可以快速运行/调整/测试示例。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>