Is it possible to capture attributes of an XML tag without creating a separate struct for that tag?

polaris · · 407 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Say I have XML like this:</p> <pre><code>&lt;ITEMS&gt; &lt;ITEM INDEX=&#34;1&#34;&gt; &lt;NAME&gt;foo&lt;/NAME&gt; &lt;TYPE ID=&#34;123&#34;&gt;bar&lt;/TYPE&gt; &lt;/ITEM&gt; &lt;/ITEMS&gt; </code></pre> <p>I can parse (unmarshal) this into a struct like this:</p> <pre><code>type Items struct { Items []Item `xml:&#34;ITEM&#34;` } type Item struct { Index int `xml:&#34;INDEX,attr&#34;` Name string `xml:&#34;NAME&#34;` Type Type `xml:&#34;TYPE&#34;` } type Type struct { ID int `xml:&#34;ID,attr&#34;` Value string `xml:&#34;,chardata&#34;` } </code></pre> <p>Is there any way to get the ID from the TYPE tag without making a separate struct for it (ie: set Item.Type to &#34;bar&#34; and Item.TypeID to &#34;123&#34;)?</p> <p>It might not look too bad in that example, but when you&#39;re working with large XML responses with dozens of tags, some that have attributes and some that don&#39;t, it gets very tedious and confusing to program and look at, not to mention the inconsistency between accessing those values (Item.Name vs Item.Type.Value).</p> <p>Obviously some kind of wrapper could be written over top of this to make accessing values and attributes more consistent, but that doesn&#39;t fix the underlying issue.</p> <p>I&#39;ve mostly read through the Go XML documentation, I don&#39;t think it mentions anything like this, though the long walls of text about how it goes about parsing the XML were somewhat confusing to keep track of, so I might have missed it somewhere in that.</p> <hr/>**评论:**<br/><br/>Spirit_of_Stallman: <pre><p>It was thought that this should work like this: <code>xml:&#34;TYPE&gt;ID,attr&#34;</code>. But for many years it does&#39;t work, and all don&#39;t care :) <a href="https://github.com/golang/go/issues/3688" rel="nofollow">Ticket</a>.</p></pre>Hakkin: <pre><p>That&#39;s unfortunate. Guess I&#39;ll have to put a wrapper around it instead of directly accessing the structs.</p> <p>Thank you for the link to the issue.</p></pre>

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

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