I'm having trouble unmarshalling the XML below, how do I find all <info>
nodes with type="Genres"
and store their values inside a []Genre
?
<manga id="4199" type="manga" name="Jinki: Extend" precision="manga">
<info type="Main title" lang="EN">Jinki: Extend</info>
<info type="Genres">action</info>
<info type="Genres">science fiction</info>
<info type="Themes">mecha</info>
<info type="Number of tankoubon">9</info>
<info type="Number of pages">186</info>
</manga>
I'm looking to store the values in structs similar to these:
// Manga struct
type Manga struct {
WorkID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Precision string `xml:"precision,attr"`
Genres []Genre `[this is the part I need help on]`
}
// Genre struct
type Genre struct {
Value string
}
I know the XML is not ideal, but it is what I have to work with, I hope you guys can help me with this.
Thanks in advance.
Since <manga>
contains a list of <info>
elements, it makes more sense to have a list of Info
structs rather than trying to translate the <info>
elements into various types. I would define the data structures like:
type Manga struct {
WorkID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Precision string `xml:"precision,attr"`
Info []Info `xml:"info"`
}
type Info struct {
Type string `xml:"type,attr"`
Value string `xml:",chardata"`
}
The output (json encoded for convenience) looks like:
{
"WorkID": 4199,
"Name": "Jinki: Extend",
"Precision": "manga",
"Info": [
{
"Type": "Main title",
"Value": "Jinki: Extend"
},
{
"Type": "Genres",
"Value": "action"
},
{
"Type": "Genres",
"Value": "science fiction"
},
{
"Type": "Themes",
"Value": "mecha"
},
{
"Type": "Number of tankoubon",
"Value": "9"
},
{
"Type": "Number of pages",
"Value": "186"
}
]
}
In case the XML won't not very large, I would just write an utility function like:
type Manga struct {
WorkID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Precision string `xml:"precision,attr"`
Info []Info `xml:"info"`
}
type Info struct {
Type string `xml:"type,attr"`
Data string `xml:",chardata"`
}
func (m *Manga) Genres() []Info {
var g []Info
for _, v := range m.Info {
if v.Type == "Genres" {
g = append(g, v)
}
}
return g
}
See it in action: https://play.golang.org/p/bebUwwbSwG