I want to map XML data to Struct object. I have following code:
package main
import (
"encoding/xml"
"fmt"
)
func main() {
type FileDetails struct {
XMLName xml.Name `xml:"FileDetails"`
FileName string
FileSize string
}
type DataRequest struct {
XMLName xml.Name `xml:"Data"`
DataRequestList []FileDetails
}
type Request struct {
XMLName xml.Name `xml:"Request"`
DataReqObject DataRequest `xml:"Data"`
}
req := Request{}
data := `
<Request>
<Data>
<FileDetails>
<FileName>abc</FileSize>
<FileSize>10</FileSize>
</FileDetails>
<FileDetails>
<FileName>pqr</FileSize>
<FileSize>20</FileSize>
</FileDetails>
</Data>
</Request>
`
err := xml.Unmarshal([]byte(data), &req)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("XMLName: %#v
", req.XMLName)
fmt.Printf("XMLName: %v
", req.DataReqObject)
fmt.Printf("XMLName: %v
", req.DataReqObject.DataRequestList[0])
}
This can also be accessed here: https://play.golang.org/p/VAMM9M2CejH
I'm getting following output with the above code:
XMLName: xml.Name{Space:"", Local:"Request"}
Data: {{ Data} []}
panic: runtime error: index out of range
Do the structs need to have diffferent structure for my data? Why is this mapping failing?