<p>Say I have XML like this:</p>
<pre><code><ITEMS>
<ITEM INDEX="1">
<NAME>foo</NAME>
<TYPE ID="123">bar</TYPE>
</ITEM>
</ITEMS>
</code></pre>
<p>I can parse (unmarshal) this into a struct like this:</p>
<pre><code>type Items struct {
Items []Item `xml:"ITEM"`
}
type Item struct {
Index int `xml:"INDEX,attr"`
Name string `xml:"NAME"`
Type Type `xml:"TYPE"`
}
type Type struct {
ID int `xml:"ID,attr"`
Value string `xml:",chardata"`
}
</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 "bar" and Item.TypeID to "123")?</p>
<p>It might not look too bad in that example, but when you're working with large XML responses with dozens of tags, some that have attributes and some that don'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't fix the underlying issue.</p>
<p>I've mostly read through the Go XML documentation, I don'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:"TYPE>ID,attr"</code>. But for many years it does't work, and all don't care :) <a href="https://github.com/golang/go/issues/3688" rel="nofollow">Ticket</a>.</p></pre>Hakkin: <pre><p>That's unfortunate. Guess I'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>
Is it possible to capture attributes of an XML tag without creating a separate struct for that tag?
polaris · · 407 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传