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

尝试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 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM