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

polaris · · 229 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m hoping to be able to do something like this...</p> <pre><code>/** source xml: &lt;things&gt; &lt;thing type=&#34;Point&#34;&gt; &lt;x&gt;1&lt;/x&gt; &lt;y&gt;2&lt;/y&gt; &lt;/thing&gt; &lt;/things&gt; */ type Thing interface { /* .. */ } // note: Point would implement Thing type Point struct { X float64 `xml:&#34;x&#34;` Y float64 `xml:&#34;y&#34;` } type SomeThings struct { Things []Thing `xml:&#34;thing&#34;` } func UnmarshalThings(xml []byte) (some *SomeThings, err error) { some = &amp;SomeThings{} err = xml.Unmarhal(xml, someThings) return } </code></pre> <p>Now, that won&#39;t work as-is. When unmarshalled there will be 1 &#34;Thing&#34; with a value of <code>nil</code>. What I&#39;m hoping is that there might be a way for me - even as a post-process step - to get the &#34;type&#34; attribute from &lt;Thing&gt;, call reflect.New to create the Point, and then unmarshal the inner XML into that.</p> <p>Is something like this doable or is there a library out there someone has written to do this already?</p> <p>Thanks!</p> <hr/>**评论:**<br/><br/>silviucm: <pre><p><a href="https://play.golang.org/p/06les9YDNg" rel="nofollow">https://play.golang.org/p/06les9YDNg</a></p></pre>stymiedcoder: <pre><p>Thank you very much for this!</p></pre>

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

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