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\n", req.XMLName)
fmt.Printf("XMLName: %v\n", req.DataReqObject)
fmt.Printf("XMLName: %v\n", 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?
DataRequestListfield.DataRequestList []FileDetails `xml:"FileDetails"`. However the fields of yourFileDetailsstruct and of the corresponding xml don't match, so that won't be fixed until you make the proper changes. (Oops they do match in the question, although not in the linked code) play.golang.org/p/IlcybvQBI9P