我有一个像这样的 xml 对象:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <directory count="2"> <entries> <entry name="alice"/> <entry name="bob"/> </entries> </directory>
现在我想将其解析为一个如下所示的 go 结构:
type entry struct { xmlname xml.name `xml:"entry"` name string `xml:"name,attr"` } type directory struct { xmlname xml.name `xml:"directory"` count string `xml:"count,attr"` entries []entry `xml:"entries"` }
如您所见,我希望 entries 成为 directory 的直接子级。这不起作用,directory.entries
始终为空。
但是,当我添加某种像这样的代理对象时,它确实有效(从此处找到的 xml->go 结构转换器获取此对象):
type Directory struct { XMLName xml.Name `xml:"directory"` Text string `xml:",chardata"` Count string `xml:"count,attr"` Entries struct { Text string `xml:",chardata"` Entry []struct { Text string `xml:",chardata"` Name string `xml:"name,attr"` } `xml:"entry"` } `xml:"entries"` }
在此版本中,数组被填充,我可以通过 directory.entries.entry[i]
访问索引 i
处的给定条目。
如何省略此处不必要的对象并直接通过 directory.entries[i]
访问条目?是否可以不构建自定义(un)编组器?
您在条目集合的 xml 定义中缺少parent>child>plant 标记 >
:
Entries []Entry `xml:"entries>entry"`