The XML format I need to unmarshal is as follows:
data := `
<table>
<name>
<code>23764</code>
<name>Smith, Jane</name>
</name>
<name>
<code>11111</code>
<name>Doe, John</name>
</name>
</table>
`
I have attempted the following structs and code to no avail:
type Customers struct {
XMLName xml.Name `xml:"table"`
Custs []Customer
}
type Customer struct {
XMLName xml.Name `xml:"name"`
Code string `xml:"code"`
Name string `xml:"name"`
}
...
var custs Customers
err := xml.Unmarshal([]byte(data), &custs)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%v", custs)
for _, cust := range custs.Custs {
fmt.Printf("Cust:\n%v\n", cust)
}
The range prints nothing out, and printing custs
only gives me {{ table} []}
The correct structure is the following:
type Customer struct {
Code string `xml:"code"`
Name string `xml:"name"`
}
type Customers struct {
Customers []Customer `xml:"name"`
}
You can try it on the playground here.
The problem is that you don't assign the xml tag for []Customer
.
The way you solved this, using xml.Name
is also correct but more verbose.
You can review working code here.
If you need to use the xml.Name
field for some reason, I would recommend
using a private field so that an exported version of the struct is not cluttered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With