I'm trying to decode XML with golang, but the following code gives an empty struct
Anyone can help?
When I run the following code, I always get
{{ packet} []}
Attached source code:
package main
import (
"fmt"
"encoding/xml"
// "io/ioutil"
)
type Field struct {
XMLName xml.Name `xml:"field"`
name string `xml:"name,attr"`
shownameg string `xml:"showname,attr"`
fields []Field
}
type Proto struct {
XMLName xml.Name `xml:"proto"`
name string `xml:"name,attr"`
shownameg string `xml:"showname,attr"`
fields []Field
}
type Packet struct {
XMLName xml.Name `xml:"packet"`
protos []Proto `xml:"proto"`
}
func main () {
data := []byte(`
<packet>
<proto name="geninfo" pos="0" showname="General information" size="122">
<field name="timestamp" pos="0" show="Jul 17, 2008 15:50:25.136434000 CST" showname="Captured Time" value="1216281025.136434000" size="122"/>
</proto>
</packet>
`)
packet := Packet{}
err := xml.Unmarshal([]byte(data), &packet)
if err != nil {
fmt.Println (err)
return
}
fmt.Println (packet)
for proto, _ := range (packet.protos) {
fmt.Println (proto)
}
}
You need to export your struct fields as per https://golang.org/pkg/encoding/xml/#Unmarshal
Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.
e.g.
type Proto struct {
XMLName xml.Name `xml:"field"`
Name string `xml:"name,attr"`
Shownameg string `xml:"showname,attr"`
Fields []Field
}