英文:
Unmarshalling XML child array into direct Go struct array
问题
我有一个像这样的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>entry"`
}
如你所见,我希望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]
直接访问条目?是否可以在不构建自定义(反)编组器的情况下实现?
英文:
I have an XML object like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<directory count="2">
<entries>
<entry name="Alice"/>
<entry name="Bob"/>
</entries>
</directory>
Now I want to parse this into a Go struct that looks like this:
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"`
}
As you can see, I'd like Entries to be a direct child of Directory. This does not work, Directory.Entries
is always empty.
It does however work when I add some kind of proxy object like this (got this from an XML->Go struct converter found here):
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"`
}
In this version, the array gets filled and I can access a given entry at index i
via Directory.Entries.Entry[i]
.
How can I omit the unneccessary object here and access the entries directly via Directory.Entries[i]
? Is it possible without building a custom (un)marshaller?
答案1
得分: 1
你在xml定义的entries集合中缺少了parent>child>plant标签>
:
Entries []Entry `xml:"entries>entry"`
去玩吧:https://go.dev/play/p/4SZT8-S8BFF
英文:
You're missing the parent>child>plant tag >
from the xml definition on the entries collection:
Entries []Entry `xml:"entries>entry"`
Go Play: https://go.dev/play/p/4SZT8-S8BFF
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论