0

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?

1
  • 3
    Add a tag to DataRequestList field. DataRequestList []FileDetails `xml:"FileDetails"`. However the fields of your FileDetails struct 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 Commented May 9, 2019 at 11:07

1 Answer 1

1

Three problems with your snippet:

#1

The tag xml:"FileDetails" is missing on DataRequestList


#2

The FileDetails struct does not match your xml in the provided playground link!


#3

<FileName> tag is closed with </FileSize> tag!


Go playground working example!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.