dty47696 2015-07-01 09:00
浏览 116
已采纳

尝试xml时出错。解组结构类型为map [string] interface {}的结构

The problem is that xml.Unmarshal of a struct with a field of type map[string]interface{} will fail with the error:

unknown type map[string]interface {}
{XMLName:{Space: Local:myStruct} Name:test Meta:map[]}

Since the Meta field of type map[string]interface{} is as far as I can define, what's inside has to be dynamically unmarshalled.

package main

import (
    "encoding/xml"
    "fmt"
)

func main() {
    var myStruct MyStruct

    // meta is as far as we know, inside meta, dynamic properties and nesting will happen
    s := `<myStruct>
        <name>test</name>
        <meta>
            <someProp>something</someProp>
            <someOtherDynamic>
                <name>test</name>
                <somethingElse>test2</somethingElse>
                <nested3>
                    <name>nested3</name>
                    <nested3elements>
                        <elem>ele1</elem>
                        <elem>ele2</elem>
                    </nested3elements>
                </nested3>
            </someOtherDynamic>
        </meta>
    </myStruct>`

    err := xml.Unmarshal([]byte(s), &myStruct)
    if err == nil {
        fmt.Printf("%+v
", myStruct)
    } else {
        fmt.Println(err)
        fmt.Printf("%+v
", myStruct)
    }
}

type MyStruct struct {
    XMLName xml.Name               `xml:"myStruct"`
    Name    string                 `xml:"name"`
    Meta    map[string]interface{} `xml:"meta,omitempty"`
}

I've made an example here: http://play.golang.org/p/lTDJzXXPwT

How can I achieve this?


My workaround "solution" so far:

http://play.golang.org/p/gQUlvkYl7k

Basically what happens is that:

  1. The Meta field got the xml annotations removed, thus being ignore from the xml.Unmashal
  2. New type, MapContainer, is created with a field: InnerXML []byte xml:",innerxml"
  3. MetaByte field of type MapContainer is added using the xml:"meta,omitempty" annotations

So in the first xml.Unmarshal we save a byte slice of the meta element's XML. Then in our custom xml unmarshal function we take that byteSlice and use the magic function NewMapXml from the mxj package, and set the Meta field of the struct to this newly created map.

This is possible thanks to the genius made this repo, https://github.com/clbanning/mxj , which can unmarshal from XML to maps.

Updated current best solution:

http://play.golang.org/p/_tw06klods

Thanks to Adam Vincze

  • 写回答

1条回答 默认 最新

  • douqun1977 2015-07-01 11:08
    关注

    depending what you need to do with meta at the end you might want to take a look at this lib: https://github.com/clbanning/mxj

    you could do it just a little nicer if you implement a custom UnmarshalXML function

    func (m *MyStruct) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
        var v struct {
            XMLName xml.Name `xml:"myStruct"`
            Name    string   `xml:"name"`
            Meta    struct {
                Inner []byte `xml:",innerxml"`
            } `xml:"meta"`
        }
    
    
        err := d.DecodeElement(&v, &start)
        if err != nil {
            return err
        }
    
        m.Name = v.Name
        myMap := make(map[string]interface{})
        // ... do the mxj magic here ... -
        // fill myMap
        m.Meta = myMap
    
    
        return nil
    }
    
    type MyStruct struct {
        Name    string
        Meta    map[string]interface{}
    }
    

    `

    that leaves your MyStruct nice and clean

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?