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

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

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题