Unmarshalling XML into interfaces created at runtime based on the XML.

polaris · 2017-10-11 09:30:10 · 646 次点击    
这是一个分享于 2017-10-11 09:30:10 的资源,其中的信息可能已经有所发展或是发生改变。

I'm hoping to be able to do something like this...

/** source xml:
<things>
    <thing type="Point">
        <x>1</x>
        <y>2</y>
    </thing>
</things>
*/

type Thing interface { /* .. */ }

// note: Point would implement Thing
type Point struct {
    X float64 `xml:"x"`
    Y float64 `xml:"y"`
}

type SomeThings struct {
    Things []Thing `xml:"thing"`
}

func UnmarshalThings(xml []byte) (some *SomeThings, err error) {
    some = &SomeThings{}
    err = xml.Unmarhal(xml, someThings)
    return
}

Now, that won't work as-is. When unmarshalled there will be 1 "Thing" with a value of nil. What I'm hoping is that there might be a way for me - even as a post-process step - to get the "type" attribute from <Thing>, call reflect.New to create the Point, and then unmarshal the inner XML into that.

Is something like this doable or is there a library out there someone has written to do this already?

Thanks!


评论:

silviucm:

https://play.golang.org/p/06les9YDNg

stymiedcoder:

Thank you very much for this!


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

646 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传