Reputation: 11788
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?
Upvotes: 0
Views: 118
Reputation: 814
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
Upvotes: 2